/usr/share/doc/nodejs/api/all.html is in nodejs 4.8.2~dfsg-1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 | <!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>About this Documentation | Node.js v4.8.2 Manual & Documentation</title>
<link rel="stylesheet" href="assets/style.css">
<link rel="stylesheet" href="assets/sh.css">
<link rel="canonical" href="all.html">
</head>
<body class="alt apidoc" id="api-section-all">
<div id="content" class="clearfix">
<div 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 class="nav-documentation" href="documentation.html">About these Docs</a></li>
<li><a class="nav-synopsis" href="synopsis.html">Usage & Example</a></li>
</ul>
<div class="line"></div>
<ul>
<li><a class="nav-assert" href="assert.html">Assertion Testing</a></li>
<li><a class="nav-buffer" href="buffer.html">Buffer</a></li>
<li><a class="nav-addons" href="addons.html">C/C++ Addons</a></li>
<li><a class="nav-child_process" href="child_process.html">Child Processes</a></li>
<li><a class="nav-cluster" href="cluster.html">Cluster</a></li>
<li><a class="nav-cli" href="cli.html">Command Line Options</a></li>
<li><a class="nav-console" href="console.html">Console</a></li>
<li><a class="nav-crypto" href="crypto.html">Crypto</a></li>
<li><a class="nav-debugger" href="debugger.html">Debugger</a></li>
<li><a class="nav-dns" href="dns.html">DNS</a></li>
<li><a class="nav-domain" href="domain.html">Domain</a></li>
<li><a class="nav-errors" href="errors.html">Errors</a></li>
<li><a class="nav-events" href="events.html">Events</a></li>
<li><a class="nav-fs" href="fs.html">File System</a></li>
<li><a class="nav-globals" href="globals.html">Globals</a></li>
<li><a class="nav-http" href="http.html">HTTP</a></li>
<li><a class="nav-https" href="https.html">HTTPS</a></li>
<li><a class="nav-modules" href="modules.html">Modules</a></li>
<li><a class="nav-net" href="net.html">Net</a></li>
<li><a class="nav-os" href="os.html">OS</a></li>
<li><a class="nav-path" href="path.html">Path</a></li>
<li><a class="nav-process" href="process.html">Process</a></li>
<li><a class="nav-punycode" href="punycode.html">Punycode</a></li>
<li><a class="nav-querystring" href="querystring.html">Query Strings</a></li>
<li><a class="nav-readline" href="readline.html">Readline</a></li>
<li><a class="nav-repl" href="repl.html">REPL</a></li>
<li><a class="nav-stream" href="stream.html">Stream</a></li>
<li><a class="nav-string_decoder" href="string_decoder.html">String Decoder</a></li>
<li><a class="nav-timers" href="timers.html">Timers</a></li>
<li><a class="nav-tls" href="tls.html">TLS/SSL</a></li>
<li><a class="nav-tty" href="tty.html">TTY</a></li>
<li><a class="nav-dgram" href="dgram.html">UDP/Datagram</a></li>
<li><a class="nav-url" href="url.html">URL</a></li>
<li><a class="nav-util" href="util.html">Utilities</a></li>
<li><a class="nav-v8" href="v8.html">V8</a></li>
<li><a class="nav-vm" href="vm.html">VM</a></li>
<li><a class="nav-zlib" href="zlib.html">ZLIB</a></li>
</ul>
<div class="line"></div>
<ul>
<li><a class="nav-https-github-com-nodejs-node" href="https://github.com/nodejs/node">GitHub Repo & Issue Tracker</a></li>
<li><a class="nav-http-groups-google-com-group-nodejs" href="http://groups.google.com/group/nodejs">Mailing List</a></li>
</ul>
</div>
<div id="column1" data-id="all" class="interior">
<header>
<h1>Node.js v4.8.2 Documentation</h1>
<div id="gtoc">
<p>
<a href="index.html" name="toc">Index</a> |
<a href="all.html">View on single page</a> |
<a href="all.json">View as JSON</a>
</p>
</div>
<hr>
</header>
<div id="toc">
<h2>Table of Contents</h2>
<ul>
<li><span class="stability_undefined"><a href="#documentation_about_this_documentation">About this Documentation</a></span><ul>
<li><span class="stability_undefined"><a href="#documentation_stability_index">Stability Index</a></span></li>
<li><span class="stability_1"><a href="#documentation_json_output">JSON Output</a></span></li>
<li><span class="stability_undefined"><a href="#documentation_syscalls_and_man_pages">Syscalls and man pages</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#synopsis_usage">Usage</a></span><ul>
<li><span class="stability_undefined"><a href="#synopsis_example">Example</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#addons_c_c_addons">C/C++ Addons</a></span><ul>
<li><span class="stability_undefined"><a href="#addons_hello_world">Hello world</a></span><ul>
<li><span class="stability_undefined"><a href="#addons_building">Building</a></span></li>
<li><span class="stability_undefined"><a href="#addons_linking_to_node_js_own_dependencies">Linking to Node.js' own dependencies</a></span></li>
<li><span class="stability_undefined"><a href="#addons_loading_addons_using_require">Loading Addons using require()</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#addons_native_abstractions_for_node_js">Native Abstractions for Node.js</a></span></li>
<li><span class="stability_undefined"><a href="#addons_addon_examples">Addon examples</a></span><ul>
<li><span class="stability_undefined"><a href="#addons_function_arguments">Function arguments</a></span></li>
<li><span class="stability_undefined"><a href="#addons_callbacks">Callbacks</a></span></li>
<li><span class="stability_undefined"><a href="#addons_object_factory">Object factory</a></span></li>
<li><span class="stability_undefined"><a href="#addons_function_factory">Function factory</a></span></li>
<li><span class="stability_undefined"><a href="#addons_wrapping_c_objects">Wrapping C++ objects</a></span></li>
<li><span class="stability_undefined"><a href="#addons_factory_of_wrapped_objects">Factory of wrapped objects</a></span></li>
<li><span class="stability_undefined"><a href="#addons_passing_wrapped_objects_around">Passing wrapped objects around</a></span></li>
<li><span class="stability_undefined"><a href="#addons_atexit_hooks">AtExit hooks</a></span><ul>
<li><span class="stability_undefined"><a href="#addons_void_atexit_callback_args">void AtExit(callback, args)</a></span></li>
</ul>
</li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#assert_assert">Assert</a></span><ul>
<li><span class="stability_undefined"><a href="#assert_assert_value_message">assert(value[, message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_deepequal_actual_expected_message">assert.deepEqual(actual, expected[, message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_deepstrictequal_actual_expected_message">assert.deepStrictEqual(actual, expected[, message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_doesnotthrow_block_error_message">assert.doesNotThrow(block[, error][, message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_equal_actual_expected_message">assert.equal(actual, expected[, message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_fail_actual_expected_message_operator">assert.fail(actual, expected, message, operator)</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_iferror_value">assert.ifError(value)</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_notdeepequal_actual_expected_message">assert.notDeepEqual(actual, expected[, message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_notdeepstrictequal_actual_expected_message">assert.notDeepStrictEqual(actual, expected[, message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_notequal_actual_expected_message">assert.notEqual(actual, expected[, message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_notstrictequal_actual_expected_message">assert.notStrictEqual(actual, expected[, message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_ok_value_message">assert.ok(value[, message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_strictequal_actual_expected_message">assert.strictEqual(actual, expected[, message])</a></span></li>
<li><span class="stability_undefined"><a href="#assert_assert_throws_block_error_message">assert.throws(block[, error][, message])</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#buffer_buffer">Buffer</a></span><ul>
<li><span class="stability_undefined"><a href="#buffer_buffer_from_buffer_alloc_and_buffer_allocunsafe"><code>Buffer.from()</code>, <code>Buffer.alloc()</code>, and <code>Buffer.allocUnsafe()</code></a></span><ul>
<li><span class="stability_undefined"><a href="#buffer_what_makes_buffer_allocunsafe_size_and_buffer_allocunsafeslow_size_unsafe">What makes <code>Buffer.allocUnsafe(size)</code> and <code>Buffer.allocUnsafeSlow(size)</code> "unsafe"?</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#buffer_buffers_and_character_encodings">Buffers and Character Encodings</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buffers_and_typedarray">Buffers and TypedArray</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buffers_and_es6_iteration">Buffers and ES6 iteration</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_the_zero_fill_buffers_command_line_option">The <code>--zero-fill-buffers</code> command line option</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_buffer">Class: Buffer</a></span><ul>
<li><span class="stability_undefined"><a href="#buffer_new_buffer_array">new Buffer(array)</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_new_buffer_buffer">new Buffer(buffer)</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_new_buffer_arraybuffer">new Buffer(arrayBuffer)</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_new_buffer_size">new Buffer(size)</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_new_buffer_str_encoding">new Buffer(str[, encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_alloc_size_fill_encoding">Class Method: Buffer.alloc(size[, fill[, encoding]])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_allocunsafe_size">Class Method: Buffer.allocUnsafe(size)</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_allocunsafeslow_size">Class Method: Buffer.allocUnsafeSlow(size)</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_bytelength_string_encoding">Class Method: Buffer.byteLength(string[, encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_compare_buf1_buf2">Class Method: Buffer.compare(buf1, buf2)</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_concat_list_totallength">Class Method: Buffer.concat(list[, totalLength])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_from_array">Class Method: Buffer.from(array)</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_from_arraybuffer">Class Method: Buffer.from(arrayBuffer)</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_from_buffer">Class Method: Buffer.from(buffer)</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_from_str_encoding">Class Method: Buffer.from(str[, encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_isbuffer_obj">Class Method: Buffer.isBuffer(obj)</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_method_buffer_isencoding_encoding">Class Method: Buffer.isEncoding(encoding)</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_index">buf[index]</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_compare_otherbuffer">buf.compare(otherBuffer)</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_copy_targetbuffer_targetstart_sourcestart_sourceend">buf.copy(targetBuffer[, targetStart[, sourceStart[, sourceEnd]]])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_entries">buf.entries()</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_equals_otherbuffer">buf.equals(otherBuffer)</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_fill_value_offset_end">buf.fill(value[, offset[, end]])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_indexof_value_byteoffset_encoding">buf.indexOf(value[, byteOffset][, encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_keys">buf.keys()</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_length">buf.length</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readdoublebe_offset_noassert">buf.readDoubleBE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readdoublele_offset_noassert">buf.readDoubleLE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readfloatbe_offset_noassert">buf.readFloatBE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readfloatle_offset_noassert">buf.readFloatLE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readint8_offset_noassert">buf.readInt8(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readint16be_offset_noassert">buf.readInt16BE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readint16le_offset_noassert">buf.readInt16LE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readint32be_offset_noassert">buf.readInt32BE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readint32le_offset_noassert">buf.readInt32LE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readintbe_offset_bytelength_noassert">buf.readIntBE(offset, byteLength[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readintle_offset_bytelength_noassert">buf.readIntLE(offset, byteLength[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readuint8_offset_noassert">buf.readUInt8(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readuint16be_offset_noassert">buf.readUInt16BE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readuint16le_offset_noassert">buf.readUInt16LE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readuint32be_offset_noassert">buf.readUInt32BE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readuint32le_offset_noassert">buf.readUInt32LE(offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readuintbe_offset_bytelength_noassert">buf.readUIntBE(offset, byteLength[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_readuintle_offset_bytelength_noassert">buf.readUIntLE(offset, byteLength[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_slice_start_end">buf.slice([start[, end]])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_tostring_encoding_start_end">buf.toString([encoding[, start[, end]]])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_tojson">buf.toJSON()</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_values">buf.values()</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_write_string_offset_length_encoding">buf.write(string[, offset[, length]][, encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writedoublebe_value_offset_noassert">buf.writeDoubleBE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writedoublele_value_offset_noassert">buf.writeDoubleLE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writefloatbe_value_offset_noassert">buf.writeFloatBE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writefloatle_value_offset_noassert">buf.writeFloatLE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeint8_value_offset_noassert">buf.writeInt8(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeint16be_value_offset_noassert">buf.writeInt16BE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeint16le_value_offset_noassert">buf.writeInt16LE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeint32be_value_offset_noassert">buf.writeInt32BE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeint32le_value_offset_noassert">buf.writeInt32LE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeintbe_value_offset_bytelength_noassert">buf.writeIntBE(value, offset, byteLength[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeintle_value_offset_bytelength_noassert">buf.writeIntLE(value, offset, byteLength[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeuint8_value_offset_noassert">buf.writeUInt8(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeuint16be_value_offset_noassert">buf.writeUInt16BE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeuint16le_value_offset_noassert">buf.writeUInt16LE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeuint32be_value_offset_noassert">buf.writeUInt32BE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeuint32le_value_offset_noassert">buf.writeUInt32LE(value, offset[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeuintbe_value_offset_bytelength_noassert">buf.writeUIntBE(value, offset, byteLength[, noAssert])</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_buf_writeuintle_value_offset_bytelength_noassert">buf.writeUIntLE(value, offset, byteLength[, noAssert])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#buffer_buffer_inspect_max_bytes">buffer.INSPECT_MAX_BYTES</a></span></li>
<li><span class="stability_undefined"><a href="#buffer_class_slowbuffer">Class: SlowBuffer</a></span><ul>
<li><span class="stability_undefined"><a href="#buffer_new_slowbuffer_size">new SlowBuffer(size)</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#child_process_child_process">Child Process</a></span><ul>
<li><span class="stability_undefined"><a href="#child_process_asynchronous_process_creation">Asynchronous Process Creation</a></span><ul>
<li><span class="stability_undefined"><a href="#child_process_spawning_bat_and_cmd_files_on_windows">Spawning <code>.bat</code> and <code>.cmd</code> files on Windows</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_process_exec_command_options_callback">child_process.exec(command[, options][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_process_execfile_file_args_options_callback">child_process.execFile(file[, args][, options][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_process_fork_modulepath_args_options">child_process.fork(modulePath[, args][, options])</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_process_spawn_command_args_options">child_process.spawn(command[, args][, options])</a></span><ul>
<li><span class="stability_undefined"><a href="#child_process_options_detached">options.detached</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_options_stdio">options.stdio</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#child_process_synchronous_process_creation">Synchronous Process Creation</a></span><ul>
<li><span class="stability_undefined"><a href="#child_process_child_process_execfilesync_file_args_options">child_process.execFileSync(file[, args][, options])</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_process_execsync_command_options">child_process.execSync(command[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_process_spawnsync_command_args_options">child_process.spawnSync(command[, args][, options])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#child_process_class_childprocess">Class: ChildProcess</a></span><ul>
<li><span class="stability_undefined"><a href="#child_process_event_close">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_event_disconnect">Event: 'disconnect'</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_event_error">Event: 'error'</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_event_exit">Event: 'exit'</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_event_message">Event: 'message'</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_connected">child.connected</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_disconnect">child.disconnect()</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_kill_signal">child.kill([signal])</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_pid">child.pid</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_send_message_sendhandle_callback">child.send(message[, sendHandle][, callback])</a></span><ul>
<li><span class="stability_undefined"><a href="#child_process_example_sending_a_server_object">Example: sending a server object</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_example_sending_a_socket_object">Example: sending a socket object</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#child_process_child_stderr">child.stderr</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_stdin">child.stdin</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_stdio">child.stdio</a></span></li>
<li><span class="stability_undefined"><a href="#child_process_child_stdout">child.stdout</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#cluster_cluster">Cluster</a></span><ul>
<li><span class="stability_undefined"><a href="#cluster_how_it_works">How It Works</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_class_worker">Class: Worker</a></span><ul>
<li><span class="stability_undefined"><a href="#cluster_event_disconnect">Event: 'disconnect'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_event_error">Event: 'error'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_event_exit">Event: 'exit'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_event_listening">Event: 'listening'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_event_message">Event: 'message'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_event_online">Event: 'online'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_worker_disconnect">worker.disconnect()</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_worker_id">worker.id</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_worker_isconnected">worker.isConnected()</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_worker_isdead">worker.isDead()</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_worker_kill_signal_sigterm">worker.kill([signal='SIGTERM'])</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_worker_process">worker.process</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_worker_send_message_sendhandle_callback">worker.send(message[, sendHandle][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_worker_suicide">worker.suicide</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#cluster_event_disconnect_1">Event: 'disconnect'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_event_exit_1">Event: 'exit'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_event_fork">Event: 'fork'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_event_listening_1">Event: 'listening'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_event_message_1">Event: 'message'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_event_online_1">Event: 'online'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_event_setup">Event: 'setup'</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_cluster_disconnect_callback">cluster.disconnect([callback])</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_cluster_fork_env">cluster.fork([env])</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_cluster_ismaster">cluster.isMaster</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_cluster_isworker">cluster.isWorker</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_cluster_schedulingpolicy">cluster.schedulingPolicy</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_cluster_settings">cluster.settings</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_cluster_setupmaster_settings">cluster.setupMaster([settings])</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_cluster_worker">cluster.worker</a></span></li>
<li><span class="stability_undefined"><a href="#cluster_cluster_workers">cluster.workers</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#cli_command_line_options">Command Line Options</a></span><ul>
<li><span class="stability_undefined"><a href="#cli_synopsis">Synopsis</a></span></li>
<li><span class="stability_undefined"><a href="#cli_options">Options</a></span><ul>
<li><span class="stability_undefined"><a href="#cli_v_version"><code>-v</code>, <code>--version</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_h_help"><code>-h</code>, <code>--help</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_e_eval_script"><code>-e</code>, <code>--eval "script"</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_p_print_script"><code>-p</code>, <code>--print "script"</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_c_check"><code>-c</code>, <code>--check</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_i_interactive"><code>-i</code>, <code>--interactive</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_r_require_module"><code>-r</code>, <code>--require module</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_no_deprecation"><code>--no-deprecation</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_trace_deprecation"><code>--trace-deprecation</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_throw_deprecation"><code>--throw-deprecation</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_trace_sync_io"><code>--trace-sync-io</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_zero_fill_buffers"><code>--zero-fill-buffers</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_track_heap_objects"><code>--track-heap-objects</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_prof_process"><code>--prof-process</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_v8_options"><code>--v8-options</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_tls_cipher_list_list"><code>--tls-cipher-list=list</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_enable_fips"><code>--enable-fips</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_force_fips"><code>--force-fips</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_icu_data_dir_file"><code>--icu-data-dir=file</code></a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#cli_environment_variables">Environment Variables</a></span><ul>
<li><span class="stability_undefined"><a href="#cli_node_debug_module"><code>NODE_DEBUG=module[,…]</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_node_path_path"><code>NODE_PATH=path[:…]</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_node_disable_colors_1"><code>NODE_DISABLE_COLORS=1</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_node_icu_data_file"><code>NODE_ICU_DATA=file</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_node_repl_history_file"><code>NODE_REPL_HISTORY=file</code></a></span></li>
<li><span class="stability_undefined"><a href="#cli_node_extra_ca_certs_file"><code>NODE_EXTRA_CA_CERTS=file</code></a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#console_console">Console</a></span><ul>
<li><span class="stability_undefined"><a href="#console_asynchronous_vs_synchronous_consoles">Asynchronous vs Synchronous Consoles</a></span></li>
<li><span class="stability_undefined"><a href="#console_class_console">Class: Console</a></span><ul>
<li><span class="stability_undefined"><a href="#console_new_console_stdout_stderr">new Console(stdout[, stderr])</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_assert_value_message">console.assert(value[, message][, ...])</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_dir_obj_options">console.dir(obj[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_error_data">console.error([data][, ...])</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_info_data">console.info([data][, ...])</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_log_data">console.log([data][, ...])</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_time_label">console.time(label)</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_timeend_label">console.timeEnd(label)</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_trace_message">console.trace(message[, ...])</a></span></li>
<li><span class="stability_undefined"><a href="#console_console_warn_data">console.warn([data][, ...])</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#crypto_crypto">Crypto</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_class_certificate">Class: Certificate</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_new_crypto_certificate">new crypto.Certificate()</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_certificate_exportchallenge_spkac">certificate.exportChallenge(spkac)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_certificate_exportpublickey_spkac">certificate.exportPublicKey(spkac)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_certificate_verifyspkac_spkac">certificate.verifySpkac(spkac)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#crypto_class_cipher">Class: Cipher</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_cipher_final_output_encoding">cipher.final([output_encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_cipher_setaad_buffer">cipher.setAAD(buffer)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_cipher_getauthtag">cipher.getAuthTag()</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_cipher_setautopadding_auto_padding_true">cipher.setAutoPadding(auto_padding=true)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_cipher_update_data_input_encoding_output_encoding">cipher.update(data[, input_encoding][, output_encoding])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#crypto_class_decipher">Class: Decipher</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_decipher_final_output_encoding">decipher.final([output_encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_decipher_setaad_buffer">decipher.setAAD(buffer)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_decipher_setauthtag_buffer">decipher.setAuthTag(buffer)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_decipher_setautopadding_auto_padding_true">decipher.setAutoPadding(auto_padding=true)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_decipher_update_data_input_encoding_output_encoding">decipher.update(data[, input_encoding][, output_encoding])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#crypto_class_diffiehellman">Class: DiffieHellman</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_diffiehellman_computesecret_other_public_key_input_encoding_output_encoding">diffieHellman.computeSecret(other_public_key[, input_encoding][, output_encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_diffiehellman_generatekeys_encoding">diffieHellman.generateKeys([encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_diffiehellman_getgenerator_encoding">diffieHellman.getGenerator([encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_diffiehellman_getprime_encoding">diffieHellman.getPrime([encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_diffiehellman_getprivatekey_encoding">diffieHellman.getPrivateKey([encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_diffiehellman_getpublickey_encoding">diffieHellman.getPublicKey([encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_diffiehellman_setprivatekey_private_key_encoding">diffieHellman.setPrivateKey(private_key[, encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_diffiehellman_setpublickey_public_key_encoding">diffieHellman.setPublicKey(public_key[, encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_diffiehellman_verifyerror">diffieHellman.verifyError</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#crypto_class_ecdh">Class: ECDH</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_ecdh_computesecret_other_public_key_input_encoding_output_encoding">ecdh.computeSecret(other_public_key[, input_encoding][, output_encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_ecdh_generatekeys_encoding_format">ecdh.generateKeys([encoding[, format]])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_ecdh_getprivatekey_encoding">ecdh.getPrivateKey([encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_ecdh_getpublickey_encoding_format">ecdh.getPublicKey([encoding[, format]])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_ecdh_setprivatekey_private_key_encoding">ecdh.setPrivateKey(private_key[, encoding])</a></span></li>
<li><span class="stability_0"><a href="#crypto_ecdh_setpublickey_public_key_encoding">ecdh.setPublicKey(public_key[, encoding])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#crypto_class_hash">Class: Hash</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_hash_digest_encoding">hash.digest([encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_hash_update_data_input_encoding">hash.update(data[, input_encoding])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#crypto_class_hmac">Class: Hmac</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_hmac_digest_encoding">hmac.digest([encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_hmac_update_data_input_encoding">hmac.update(data[, input_encoding])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#crypto_class_sign">Class: Sign</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_sign_sign_private_key_output_format">sign.sign(private_key[, output_format])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_sign_update_data_input_encoding">sign.update(data[, input_encoding])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#crypto_class_verify">Class: Verify</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_verifier_update_data_input_encoding">verifier.update(data[, input_encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_verifier_verify_object_signature_signature_format">verifier.verify(object, signature[, signature_format])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#crypto_crypto_module_methods_and_properties"><code>crypto</code> module methods and properties</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_crypto_default_encoding">crypto.DEFAULT_ENCODING</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_createcipher_algorithm_password">crypto.createCipher(algorithm, password)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_createcipheriv_algorithm_key_iv">crypto.createCipheriv(algorithm, key, iv)</a></span></li>
<li><span class="stability_0"><a href="#crypto_crypto_createcredentials_details">crypto.createCredentials(details)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_createdecipher_algorithm_password">crypto.createDecipher(algorithm, password)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_createdecipheriv_algorithm_key_iv">crypto.createDecipheriv(algorithm, key, iv)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_creatediffiehellman_prime_prime_encoding_generator_generator_encoding">crypto.createDiffieHellman(prime[, prime_encoding][, generator][, generator_encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_creatediffiehellman_prime_length_generator">crypto.createDiffieHellman(prime_length[, generator])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_createecdh_curve_name">crypto.createECDH(curve_name)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_createhash_algorithm">crypto.createHash(algorithm)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_createhmac_algorithm_key">crypto.createHmac(algorithm, key)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_createsign_algorithm">crypto.createSign(algorithm)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_createverify_algorithm">crypto.createVerify(algorithm)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_getciphers">crypto.getCiphers()</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_getcurves">crypto.getCurves()</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_getdiffiehellman_group_name">crypto.getDiffieHellman(group_name)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_gethashes">crypto.getHashes()</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback">crypto.pbkdf2(password, salt, iterations, keylen[, digest], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_pbkdf2sync_password_salt_iterations_keylen_digest">crypto.pbkdf2Sync(password, salt, iterations, keylen[, digest])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_privatedecrypt_private_key_buffer">crypto.privateDecrypt(private_key, buffer)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_privateencrypt_private_key_buffer">crypto.privateEncrypt(private_key, buffer)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_publicdecrypt_public_key_buffer">crypto.publicDecrypt(public_key, buffer)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_publicencrypt_public_key_buffer">crypto.publicEncrypt(public_key, buffer)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_randombytes_size_callback">crypto.randomBytes(size[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_crypto_setengine_engine_flags">crypto.setEngine(engine[, flags])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#crypto_notes">Notes</a></span><ul>
<li><span class="stability_undefined"><a href="#crypto_legacy_streams_api_pre_node_js_v0_10">Legacy Streams API (pre Node.js v0.10)</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_recent_ecdh_changes">Recent ECDH Changes</a></span></li>
<li><span class="stability_undefined"><a href="#crypto_support_for_weak_or_compromised_algorithms">Support for weak or compromised algorithms</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#debugger_debugger">Debugger</a></span><ul>
<li><span class="stability_undefined"><a href="#debugger_watchers">Watchers</a></span></li>
<li><span class="stability_undefined"><a href="#debugger_command_reference">Command reference</a></span><ul>
<li><span class="stability_undefined"><a href="#debugger_stepping">Stepping</a></span></li>
<li><span class="stability_undefined"><a href="#debugger_breakpoints">Breakpoints</a></span></li>
<li><span class="stability_undefined"><a href="#debugger_information">Information</a></span></li>
<li><span class="stability_undefined"><a href="#debugger_execution_control">Execution control</a></span></li>
<li><span class="stability_undefined"><a href="#debugger_various">Various</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#debugger_advanced_usage">Advanced Usage</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#dgram_udp_datagram_sockets">UDP / Datagram Sockets</a></span><ul>
<li><span class="stability_undefined"><a href="#dgram_class_dgram_socket">Class: dgram.Socket</a></span><ul>
<li><span class="stability_undefined"><a href="#dgram_event_close">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_event_error">Event: 'error'</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_event_listening">Event: 'listening'</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_event_message">Event: 'message'</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_addmembership_multicastaddress_multicastinterface">socket.addMembership(multicastAddress[, multicastInterface])</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_address">socket.address()</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_bind_port_address_callback">socket.bind([port][, address][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_bind_options_callback">socket.bind(options[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_close_callback">socket.close([callback])</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_dropmembership_multicastaddress_multicastinterface">socket.dropMembership(multicastAddress[, multicastInterface])</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_send_buf_offset_length_port_address_callback">socket.send(buf, offset, length, port, address[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_setbroadcast_flag">socket.setBroadcast(flag)</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_setmulticastloopback_flag">socket.setMulticastLoopback(flag)</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_setmulticastttl_ttl">socket.setMulticastTTL(ttl)</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_setttl_ttl">socket.setTTL(ttl)</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_ref">socket.ref()</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_socket_unref">socket.unref()</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_change_to_asynchronous_socket_bind_behavior">Change to asynchronous <code>socket.bind()</code> behavior</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#dgram_dgram_module_functions"><code>dgram</code> module functions</a></span><ul>
<li><span class="stability_undefined"><a href="#dgram_dgram_createsocket_options_callback">dgram.createSocket(options[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#dgram_dgram_createsocket_type_callback">dgram.createSocket(type[, callback])</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#dns_dns">DNS</a></span><ul>
<li><span class="stability_undefined"><a href="#dns_dns_getservers">dns.getServers()</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_lookup_hostname_options_callback">dns.lookup(hostname[, options], callback)</a></span><ul>
<li><span class="stability_undefined"><a href="#dns_supported_getaddrinfo_flags">Supported getaddrinfo flags</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#dns_dns_lookupservice_address_port_callback">dns.lookupService(address, port, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolve_hostname_rrtype_callback">dns.resolve(hostname[, rrtype], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolve4_hostname_callback">dns.resolve4(hostname, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolve6_hostname_callback">dns.resolve6(hostname, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolvecname_hostname_callback">dns.resolveCname(hostname, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolvemx_hostname_callback">dns.resolveMx(hostname, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolvenaptr_hostname_callback">dns.resolveNaptr(hostname, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolvens_hostname_callback">dns.resolveNs(hostname, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolvesoa_hostname_callback">dns.resolveSoa(hostname, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolvesrv_hostname_callback">dns.resolveSrv(hostname, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolvetxt_hostname_callback">dns.resolveTxt(hostname, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_reverse_ip_callback">dns.reverse(ip, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_setservers_servers">dns.setServers(servers)</a></span></li>
<li><span class="stability_undefined"><a href="#dns_error_codes">Error codes</a></span></li>
<li><span class="stability_undefined"><a href="#dns_implementation_considerations">Implementation considerations</a></span><ul>
<li><span class="stability_undefined"><a href="#dns_dns_lookup"><code>dns.lookup()</code></a></span></li>
<li><span class="stability_undefined"><a href="#dns_dns_resolve_dns_resolve_and_dns_reverse"><code>dns.resolve()</code>, <code>dns.resolve*()</code> and <code>dns.reverse()</code></a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_0"><a href="#domain_domain">Domain</a></span><ul>
<li><span class="stability_undefined"><a href="#domain_warning_don_t_ignore_errors">Warning: Don't Ignore Errors!</a></span></li>
<li><span class="stability_undefined"><a href="#domain_additions_to_error_objects">Additions to Error objects</a></span></li>
<li><span class="stability_undefined"><a href="#domain_implicit_binding">Implicit Binding</a></span></li>
<li><span class="stability_undefined"><a href="#domain_explicit_binding">Explicit Binding</a></span></li>
<li><span class="stability_undefined"><a href="#domain_domain_create">domain.create()</a></span></li>
<li><span class="stability_undefined"><a href="#domain_class_domain">Class: Domain</a></span><ul>
<li><span class="stability_undefined"><a href="#domain_domain_run_fn_arg">domain.run(fn[, arg][, ...])</a></span></li>
<li><span class="stability_undefined"><a href="#domain_domain_members">domain.members</a></span></li>
<li><span class="stability_undefined"><a href="#domain_domain_add_emitter">domain.add(emitter)</a></span></li>
<li><span class="stability_undefined"><a href="#domain_domain_remove_emitter">domain.remove(emitter)</a></span></li>
<li><span class="stability_undefined"><a href="#domain_domain_bind_callback">domain.bind(callback)</a></span><ul>
<li><span class="stability_undefined"><a href="#domain_example">Example</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#domain_domain_intercept_callback">domain.intercept(callback)</a></span><ul>
<li><span class="stability_undefined"><a href="#domain_example_1">Example</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#domain_domain_enter">domain.enter()</a></span></li>
<li><span class="stability_undefined"><a href="#domain_domain_exit">domain.exit()</a></span></li>
<li><span class="stability_0"><a href="#domain_domain_dispose">domain.dispose()</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#errors_errors">Errors</a></span><ul>
<li><span class="stability_undefined"><a href="#errors_error_propagation_and_interception">Error Propagation and Interception</a></span><ul>
<li><span class="stability_undefined"><a href="#errors_node_js_style_callbacks">Node.js style callbacks</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#errors_class_error">Class: Error</a></span><ul>
<li><span class="stability_undefined"><a href="#errors_new_error_message">new Error(message)</a></span></li>
<li><span class="stability_undefined"><a href="#errors_error_capturestacktrace_targetobject_constructoropt">Error.captureStackTrace(targetObject[, constructorOpt])</a></span></li>
<li><span class="stability_undefined"><a href="#errors_error_stacktracelimit">Error.stackTraceLimit</a></span><ul>
<li><span class="stability_undefined"><a href="#errors_error_message">error.message</a></span></li>
<li><span class="stability_undefined"><a href="#errors_error_stack">error.stack</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#errors_class_rangeerror">Class: RangeError</a></span></li>
<li><span class="stability_undefined"><a href="#errors_class_referenceerror">Class: ReferenceError</a></span></li>
<li><span class="stability_undefined"><a href="#errors_class_syntaxerror">Class: SyntaxError</a></span></li>
<li><span class="stability_undefined"><a href="#errors_class_typeerror">Class: TypeError</a></span></li>
<li><span class="stability_undefined"><a href="#errors_exceptions_vs_errors">Exceptions vs. Errors</a></span></li>
<li><span class="stability_undefined"><a href="#errors_system_errors">System Errors</a></span><ul>
<li><span class="stability_undefined"><a href="#errors_class_system_error">Class: System Error</a></span><ul>
<li><span class="stability_undefined"><a href="#errors_error_code">error.code</a></span></li>
<li><span class="stability_undefined"><a href="#errors_error_errno">error.errno</a></span></li>
<li><span class="stability_undefined"><a href="#errors_error_syscall">error.syscall</a></span></li>
<li><span class="stability_undefined"><a href="#errors_error_path">error.path</a></span></li>
<li><span class="stability_undefined"><a href="#errors_error_address">error.address</a></span></li>
<li><span class="stability_undefined"><a href="#errors_error_port">error.port</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#errors_common_system_errors">Common System Errors</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#events_events">Events</a></span><ul>
<li><span class="stability_undefined"><a href="#events_passing_arguments_and_this_to_listeners">Passing arguments and <code>this</code> to listeners</a></span></li>
<li><span class="stability_undefined"><a href="#events_asynchronous_vs_synchronous">Asynchronous vs. Synchronous</a></span></li>
<li><span class="stability_undefined"><a href="#events_handling_events_only_once">Handling events only once</a></span></li>
<li><span class="stability_undefined"><a href="#events_error_events">Error events</a></span></li>
<li><span class="stability_undefined"><a href="#events_class_eventemitter">Class: EventEmitter</a></span><ul>
<li><span class="stability_undefined"><a href="#events_event_newlistener">Event: 'newListener'</a></span></li>
<li><span class="stability_undefined"><a href="#events_event_removelistener">Event: 'removeListener'</a></span></li>
<li><span class="stability_0"><a href="#events_eventemitter_listenercount_emitter_eventname">EventEmitter.listenerCount(emitter, eventName)</a></span></li>
<li><span class="stability_undefined"><a href="#events_eventemitter_defaultmaxlisteners">EventEmitter.defaultMaxListeners</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_addlistener_eventname_listener">emitter.addListener(eventName, listener)</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_emit_eventname_arg1_arg2">emitter.emit(eventName[, arg1][, arg2][, ...])</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_getmaxlisteners">emitter.getMaxListeners()</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_listenercount_eventname">emitter.listenerCount(eventName)</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_listeners_eventname">emitter.listeners(eventName)</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_on_eventname_listener">emitter.on(eventName, listener)</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_once_eventname_listener">emitter.once(eventName, listener)</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_removealllisteners_eventname">emitter.removeAllListeners([eventName])</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_removelistener_eventname_listener">emitter.removeListener(eventName, listener)</a></span></li>
<li><span class="stability_undefined"><a href="#events_emitter_setmaxlisteners_n">emitter.setMaxListeners(n)</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#fs_file_system">File System</a></span><ul>
<li><span class="stability_undefined"><a href="#fs_class_fs_fswatcher">Class: fs.FSWatcher</a></span><ul>
<li><span class="stability_undefined"><a href="#fs_event_change">Event: 'change'</a></span></li>
<li><span class="stability_undefined"><a href="#fs_event_error">Event: 'error'</a></span></li>
<li><span class="stability_undefined"><a href="#fs_watcher_close">watcher.close()</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#fs_class_fs_readstream">Class: fs.ReadStream</a></span><ul>
<li><span class="stability_undefined"><a href="#fs_event_open">Event: 'open'</a></span></li>
<li><span class="stability_undefined"><a href="#fs_event_close">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#fs_readstream_path">readStream.path</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#fs_class_fs_stats">Class: fs.Stats</a></span><ul>
<li><span class="stability_undefined"><a href="#fs_stat_time_values">Stat Time Values</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#fs_class_fs_writestream">Class: fs.WriteStream</a></span><ul>
<li><span class="stability_undefined"><a href="#fs_event_open_1">Event: 'open'</a></span></li>
<li><span class="stability_undefined"><a href="#fs_event_close_1">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#fs_writestream_byteswritten">writeStream.bytesWritten</a></span></li>
<li><span class="stability_undefined"><a href="#fs_writestream_path">writeStream.path</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#fs_fs_access_path_mode_callback">fs.access(path[, mode], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_accesssync_path_mode">fs.accessSync(path[, mode])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_appendfile_file_data_options_callback">fs.appendFile(file, data[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_appendfilesync_file_data_options">fs.appendFileSync(file, data[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_chmod_path_mode_callback">fs.chmod(path, mode, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_chmodsync_path_mode">fs.chmodSync(path, mode)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_chown_path_uid_gid_callback">fs.chown(path, uid, gid, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_chownsync_path_uid_gid">fs.chownSync(path, uid, gid)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_close_fd_callback">fs.close(fd, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_closesync_fd">fs.closeSync(fd)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_createreadstream_path_options">fs.createReadStream(path[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_createwritestream_path_options">fs.createWriteStream(path[, options])</a></span></li>
<li><span class="stability_0"><a href="#fs_fs_exists_path_callback">fs.exists(path, callback)</a></span></li>
<li><span class="stability_0"><a href="#fs_fs_existssync_path">fs.existsSync(path)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_fchmod_fd_mode_callback">fs.fchmod(fd, mode, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_fchmodsync_fd_mode">fs.fchmodSync(fd, mode)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_fchown_fd_uid_gid_callback">fs.fchown(fd, uid, gid, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_fchownsync_fd_uid_gid">fs.fchownSync(fd, uid, gid)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_fdatasync_fd_callback">fs.fdatasync(fd, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_fdatasyncsync_fd">fs.fdatasyncSync(fd)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_fstat_fd_callback">fs.fstat(fd, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_fstatsync_fd">fs.fstatSync(fd)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_fsync_fd_callback">fs.fsync(fd, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_fsyncsync_fd">fs.fsyncSync(fd)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_ftruncate_fd_len_callback">fs.ftruncate(fd, len, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_ftruncatesync_fd_len">fs.ftruncateSync(fd, len)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_futimes_fd_atime_mtime_callback">fs.futimes(fd, atime, mtime, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_futimessync_fd_atime_mtime">fs.futimesSync(fd, atime, mtime)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_lchmod_path_mode_callback">fs.lchmod(path, mode, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_lchmodsync_path_mode">fs.lchmodSync(path, mode)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_lchown_path_uid_gid_callback">fs.lchown(path, uid, gid, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_lchownsync_path_uid_gid">fs.lchownSync(path, uid, gid)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_link_srcpath_dstpath_callback">fs.link(srcpath, dstpath, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_linksync_srcpath_dstpath">fs.linkSync(srcpath, dstpath)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_lstat_path_callback">fs.lstat(path, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_lstatsync_path">fs.lstatSync(path)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_mkdir_path_mode_callback">fs.mkdir(path[, mode], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_mkdirsync_path_mode">fs.mkdirSync(path[, mode])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_mkdtemp_prefix_callback">fs.mkdtemp(prefix, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_mkdtempsync_template">fs.mkdtempSync(template)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_open_path_flags_mode_callback">fs.open(path, flags[, mode], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_opensync_path_flags_mode">fs.openSync(path, flags[, mode])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_read_fd_buffer_offset_length_position_callback">fs.read(fd, buffer, offset, length, position, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_readdir_path_callback">fs.readdir(path, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_readdirsync_path">fs.readdirSync(path)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_readfile_file_options_callback">fs.readFile(file[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_readfilesync_file_options">fs.readFileSync(file[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_readlink_path_callback">fs.readlink(path, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_readlinksync_path">fs.readlinkSync(path)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_realpath_path_cache_callback">fs.realpath(path[, cache], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_readsync_fd_buffer_offset_length_position">fs.readSync(fd, buffer, offset, length, position)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_realpathsync_path_cache">fs.realpathSync(path[, cache])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_rename_oldpath_newpath_callback">fs.rename(oldPath, newPath, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_renamesync_oldpath_newpath">fs.renameSync(oldPath, newPath)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_rmdir_path_callback">fs.rmdir(path, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_rmdirsync_path">fs.rmdirSync(path)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_stat_path_callback">fs.stat(path, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_statsync_path">fs.statSync(path)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_symlink_target_path_type_callback">fs.symlink(target, path[, type], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_symlinksync_target_path_type">fs.symlinkSync(target, path[, type])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_truncate_path_len_callback">fs.truncate(path, len, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_truncatesync_path_len">fs.truncateSync(path, len)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_unlink_path_callback">fs.unlink(path, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_unlinksync_path">fs.unlinkSync(path)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_unwatchfile_filename_listener">fs.unwatchFile(filename[, listener])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_utimes_path_atime_mtime_callback">fs.utimes(path, atime, mtime, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_utimessync_path_atime_mtime">fs.utimesSync(path, atime, mtime)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_watch_filename_options_listener">fs.watch(filename[, options][, listener])</a></span><ul>
<li><span class="stability_undefined"><a href="#fs_caveats">Caveats</a></span><ul>
<li><span class="stability_undefined"><a href="#fs_availability">Availability</a></span></li>
<li><span class="stability_undefined"><a href="#fs_inodes">Inodes</a></span></li>
<li><span class="stability_undefined"><a href="#fs_filename_argument">Filename Argument</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#fs_fs_watchfile_filename_options_listener">fs.watchFile(filename[, options], listener)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_write_fd_buffer_offset_length_position_callback">fs.write(fd, buffer, offset, length[, position], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_write_fd_data_position_encoding_callback">fs.write(fd, data[, position[, encoding]], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_writefile_file_data_options_callback">fs.writeFile(file, data[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_writefilesync_file_data_options">fs.writeFileSync(file, data[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_writesync_fd_buffer_offset_length_position">fs.writeSync(fd, buffer, offset, length[, position])</a></span></li>
<li><span class="stability_undefined"><a href="#fs_fs_writesync_fd_data_position_encoding">fs.writeSync(fd, data[, position[, encoding]])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#globals_global_objects">Global Objects</a></span><ul>
<li><span class="stability_undefined"><a href="#globals_class_buffer">Class: Buffer</a></span></li>
<li><span class="stability_undefined"><a href="#globals_dirname">__dirname</a></span></li>
<li><span class="stability_undefined"><a href="#globals_filename">__filename</a></span></li>
<li><span class="stability_undefined"><a href="#globals_clearimmediate_immediateobject">clearImmediate(immediateObject)</a></span></li>
<li><span class="stability_undefined"><a href="#globals_clearinterval_intervalobject">clearInterval(intervalObject)</a></span></li>
<li><span class="stability_undefined"><a href="#globals_cleartimeout_timeoutobject">clearTimeout(timeoutObject)</a></span></li>
<li><span class="stability_undefined"><a href="#globals_console">console</a></span></li>
<li><span class="stability_undefined"><a href="#globals_exports">exports</a></span></li>
<li><span class="stability_undefined"><a href="#globals_global">global</a></span></li>
<li><span class="stability_undefined"><a href="#globals_module">module</a></span></li>
<li><span class="stability_undefined"><a href="#globals_process">process</a></span></li>
<li><span class="stability_undefined"><a href="#globals_require">require()</a></span><ul>
<li><span class="stability_undefined"><a href="#globals_require_cache">require.cache</a></span></li>
<li><span class="stability_0"><a href="#globals_require_extensions">require.extensions</a></span></li>
<li><span class="stability_undefined"><a href="#globals_require_resolve">require.resolve()</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#globals_setimmediate_callback_arg">setImmediate(callback[, arg][, ...])</a></span></li>
<li><span class="stability_undefined"><a href="#globals_setinterval_callback_delay_arg">setInterval(callback, delay[, arg][, ...])</a></span></li>
<li><span class="stability_undefined"><a href="#globals_settimeout_callback_delay_arg">setTimeout(callback, delay[, arg][, ...])</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#http_http">HTTP</a></span><ul>
<li><span class="stability_undefined"><a href="#http_class_http_agent">Class: http.Agent</a></span><ul>
<li><span class="stability_undefined"><a href="#http_new_agent_options">new Agent([options])</a></span></li>
<li><span class="stability_undefined"><a href="#http_agent_destroy">agent.destroy()</a></span></li>
<li><span class="stability_undefined"><a href="#http_agent_freesockets">agent.freeSockets</a></span></li>
<li><span class="stability_undefined"><a href="#http_agent_getname_options">agent.getName(options)</a></span></li>
<li><span class="stability_undefined"><a href="#http_agent_maxfreesockets">agent.maxFreeSockets</a></span></li>
<li><span class="stability_undefined"><a href="#http_agent_maxsockets">agent.maxSockets</a></span></li>
<li><span class="stability_undefined"><a href="#http_agent_requests">agent.requests</a></span></li>
<li><span class="stability_undefined"><a href="#http_agent_sockets">agent.sockets</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http_class_http_clientrequest">Class: http.ClientRequest</a></span><ul>
<li><span class="stability_undefined"><a href="#http_event_abort">Event: 'abort'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_aborted">Event: 'aborted'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_connect">Event: 'connect'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_continue">Event: 'continue'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_response">Event: 'response'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_socket">Event: 'socket'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_upgrade">Event: 'upgrade'</a></span></li>
<li><span class="stability_undefined"><a href="#http_request_abort">request.abort()</a></span></li>
<li><span class="stability_undefined"><a href="#http_request_aborted">request.aborted</a></span></li>
<li><span class="stability_undefined"><a href="#http_request_end_data_encoding_callback">request.end([data][, encoding][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http_request_flushheaders">request.flushHeaders()</a></span></li>
<li><span class="stability_undefined"><a href="#http_request_setnodelay_nodelay">request.setNoDelay([noDelay])</a></span></li>
<li><span class="stability_undefined"><a href="#http_request_setsocketkeepalive_enable_initialdelay">request.setSocketKeepAlive([enable][, initialDelay])</a></span></li>
<li><span class="stability_undefined"><a href="#http_request_settimeout_timeout_callback">request.setTimeout(timeout[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http_request_write_chunk_encoding_callback">request.write(chunk[, encoding][, callback])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http_class_http_server">Class: http.Server</a></span><ul>
<li><span class="stability_undefined"><a href="#http_event_checkcontinue">Event: 'checkContinue'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_clienterror">Event: 'clientError'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_close">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_connect_1">Event: 'connect'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_connection">Event: 'connection'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_request">Event: 'request'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_upgrade_1">Event: 'upgrade'</a></span></li>
<li><span class="stability_undefined"><a href="#http_server_close_callback">server.close([callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http_server_listen_handle_callback">server.listen(handle[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http_server_listen_path_callback">server.listen(path[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http_server_listen_port_hostname_backlog_callback">server.listen([port][, hostname][, backlog][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http_server_maxheaderscount">server.maxHeadersCount</a></span></li>
<li><span class="stability_undefined"><a href="#http_server_settimeout_msecs_callback">server.setTimeout(msecs, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#http_server_timeout">server.timeout</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http_class_http_serverresponse">Class: http.ServerResponse</a></span><ul>
<li><span class="stability_undefined"><a href="#http_event_close_1">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_finish">Event: 'finish'</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_addtrailers_headers">response.addTrailers(headers)</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_end_data_encoding_callback">response.end([data][, encoding][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_finished">response.finished</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_getheader_name">response.getHeader(name)</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_headerssent">response.headersSent</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_removeheader_name">response.removeHeader(name)</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_senddate">response.sendDate</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_setheader_name_value">response.setHeader(name, value)</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_settimeout_msecs_callback">response.setTimeout(msecs, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_statuscode">response.statusCode</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_statusmessage">response.statusMessage</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_write_chunk_encoding_callback">response.write(chunk[, encoding][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_writecontinue">response.writeContinue()</a></span></li>
<li><span class="stability_undefined"><a href="#http_response_writehead_statuscode_statusmessage_headers">response.writeHead(statusCode[, statusMessage][, headers])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http_class_http_incomingmessage">Class: http.IncomingMessage</a></span><ul>
<li><span class="stability_undefined"><a href="#http_event_aborted_1">Event: 'aborted'</a></span></li>
<li><span class="stability_undefined"><a href="#http_event_close_2">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_destroy_error">message.destroy([error])</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_headers">message.headers</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_httpversion">message.httpVersion</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_method">message.method</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_rawheaders">message.rawHeaders</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_rawtrailers">message.rawTrailers</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_settimeout_msecs_callback">message.setTimeout(msecs, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_statuscode">message.statusCode</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_statusmessage">message.statusMessage</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_socket">message.socket</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_trailers">message.trailers</a></span></li>
<li><span class="stability_undefined"><a href="#http_message_url">message.url</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#http_http_methods">http.METHODS</a></span></li>
<li><span class="stability_undefined"><a href="#http_http_status_codes">http.STATUS_CODES</a></span></li>
<li><span class="stability_0"><a href="#http_http_createclient_port_host">http.createClient([port][, host])</a></span></li>
<li><span class="stability_undefined"><a href="#http_http_createserver_requestlistener">http.createServer([requestListener])</a></span></li>
<li><span class="stability_undefined"><a href="#http_http_get_options_callback">http.get(options[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#http_http_globalagent">http.globalAgent</a></span></li>
<li><span class="stability_undefined"><a href="#http_http_request_options_callback">http.request(options[, callback])</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#https_https">HTTPS</a></span><ul>
<li><span class="stability_undefined"><a href="#https_class_https_agent">Class: https.Agent</a></span></li>
<li><span class="stability_undefined"><a href="#https_class_https_server">Class: https.Server</a></span><ul>
<li><span class="stability_undefined"><a href="#https_server_settimeout_msecs_callback">server.setTimeout(msecs, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#https_server_timeout">server.timeout</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#https_https_createserver_options_requestlistener">https.createServer(options[, requestListener])</a></span><ul>
<li><span class="stability_undefined"><a href="#https_server_close_callback">server.close([callback])</a></span></li>
<li><span class="stability_undefined"><a href="#https_server_listen_handle_callback">server.listen(handle[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#https_server_listen_path_callback">server.listen(path[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#https_server_listen_port_host_backlog_callback">server.listen(port[, host][, backlog][, callback])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#https_https_get_options_callback">https.get(options, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#https_https_globalagent">https.globalAgent</a></span></li>
<li><span class="stability_undefined"><a href="#https_https_request_options_callback">https.request(options, callback)</a></span></li>
</ul>
</li>
<li><span class="stability_3"><a href="#modules_modules">Modules</a></span><ul>
<li><span class="stability_undefined"><a href="#modules_accessing_the_main_module">Accessing the main module</a></span></li>
<li><span class="stability_undefined"><a href="#modules_addenda_package_manager_tips">Addenda: Package Manager Tips</a></span></li>
<li><span class="stability_undefined"><a href="#modules_all_together">All Together...</a></span></li>
<li><span class="stability_undefined"><a href="#modules_caching">Caching</a></span><ul>
<li><span class="stability_undefined"><a href="#modules_module_caching_caveats">Module Caching Caveats</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#modules_core_modules">Core Modules</a></span></li>
<li><span class="stability_undefined"><a href="#modules_cycles">Cycles</a></span></li>
<li><span class="stability_undefined"><a href="#modules_file_modules">File Modules</a></span></li>
<li><span class="stability_undefined"><a href="#modules_folders_as_modules">Folders as Modules</a></span></li>
<li><span class="stability_undefined"><a href="#modules_loading_from_node_modules_folders">Loading from <code>node_modules</code> Folders</a></span></li>
<li><span class="stability_undefined"><a href="#modules_loading_from_the_global_folders">Loading from the global folders</a></span></li>
<li><span class="stability_undefined"><a href="#modules_the_module_wrapper">The module wrapper</a></span></li>
<li><span class="stability_undefined"><a href="#modules_the_module_object">The <code>module</code> Object</a></span><ul>
<li><span class="stability_undefined"><a href="#modules_module_children">module.children</a></span></li>
<li><span class="stability_undefined"><a href="#modules_module_exports">module.exports</a></span><ul>
<li><span class="stability_undefined"><a href="#modules_exports_shortcut">exports shortcut</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#modules_module_filename">module.filename</a></span></li>
<li><span class="stability_undefined"><a href="#modules_module_id">module.id</a></span></li>
<li><span class="stability_undefined"><a href="#modules_module_loaded">module.loaded</a></span></li>
<li><span class="stability_undefined"><a href="#modules_module_parent">module.parent</a></span></li>
<li><span class="stability_undefined"><a href="#modules_module_require_id">module.require(id)</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#net_net">Net</a></span><ul>
<li><span class="stability_undefined"><a href="#net_class_net_server">Class: net.Server</a></span><ul>
<li><span class="stability_undefined"><a href="#net_event_close">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_connection">Event: 'connection'</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_error">Event: 'error'</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_listening">Event: 'listening'</a></span></li>
<li><span class="stability_undefined"><a href="#net_server_address">server.address()</a></span></li>
<li><span class="stability_undefined"><a href="#net_server_close_callback">server.close([callback])</a></span></li>
<li><span class="stability_0"><a href="#net_server_connections">server.connections</a></span></li>
<li><span class="stability_undefined"><a href="#net_server_getconnections_callback">server.getConnections(callback)</a></span></li>
<li><span class="stability_undefined"><a href="#net_server_listen_handle_backlog_callback">server.listen(handle[, backlog][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#net_server_listen_options_callback">server.listen(options[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#net_server_listen_path_backlog_callback">server.listen(path[, backlog][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#net_server_listen_port_hostname_backlog_callback">server.listen([port][, hostname][, backlog][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#net_server_maxconnections">server.maxConnections</a></span></li>
<li><span class="stability_undefined"><a href="#net_server_ref">server.ref()</a></span></li>
<li><span class="stability_undefined"><a href="#net_server_unref">server.unref()</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#net_class_net_socket">Class: net.Socket</a></span><ul>
<li><span class="stability_undefined"><a href="#net_new_net_socket_options">new net.Socket([options])</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_close_1">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_connect">Event: 'connect'</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_data">Event: 'data'</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_drain">Event: 'drain'</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_end">Event: 'end'</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_error_1">Event: 'error'</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_lookup">Event: 'lookup'</a></span></li>
<li><span class="stability_undefined"><a href="#net_event_timeout">Event: 'timeout'</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_address">socket.address()</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_buffersize">socket.bufferSize</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_bytesread">socket.bytesRead</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_byteswritten">socket.bytesWritten</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_connect_options_connectlistener">socket.connect(options[, connectListener])</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_connect_path_connectlistener">socket.connect(path[, connectListener])</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_connect_port_host_connectlistener">socket.connect(port[, host][, connectListener])</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_destroy">socket.destroy()</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_destroyed">socket.destroyed</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_end_data_encoding">socket.end([data][, encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_localaddress">socket.localAddress</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_localport">socket.localPort</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_pause">socket.pause()</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_ref">socket.ref()</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_remoteaddress">socket.remoteAddress</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_remotefamily">socket.remoteFamily</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_remoteport">socket.remotePort</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_resume">socket.resume()</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_setencoding_encoding">socket.setEncoding([encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_setkeepalive_enable_initialdelay">socket.setKeepAlive([enable][, initialDelay])</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_setnodelay_nodelay">socket.setNoDelay([noDelay])</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_settimeout_timeout_callback">socket.setTimeout(timeout[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_unref">socket.unref()</a></span></li>
<li><span class="stability_undefined"><a href="#net_socket_write_data_encoding_callback">socket.write(data[, encoding][, callback])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#net_net_connect_options_connectlistener">net.connect(options[, connectListener])</a></span></li>
<li><span class="stability_undefined"><a href="#net_net_connect_path_connectlistener">net.connect(path[, connectListener])</a></span></li>
<li><span class="stability_undefined"><a href="#net_net_connect_port_host_connectlistener">net.connect(port[, host][, connectListener])</a></span></li>
<li><span class="stability_undefined"><a href="#net_net_createconnection_options_connectlistener">net.createConnection(options[, connectListener])</a></span></li>
<li><span class="stability_undefined"><a href="#net_net_createconnection_path_connectlistener">net.createConnection(path[, connectListener])</a></span></li>
<li><span class="stability_undefined"><a href="#net_net_createconnection_port_host_connectlistener">net.createConnection(port[, host][, connectListener])</a></span></li>
<li><span class="stability_undefined"><a href="#net_net_createserver_options_connectionlistener">net.createServer([options][, connectionListener])</a></span></li>
<li><span class="stability_undefined"><a href="#net_net_isip_input">net.isIP(input)</a></span></li>
<li><span class="stability_undefined"><a href="#net_net_isipv4_input">net.isIPv4(input)</a></span></li>
<li><span class="stability_undefined"><a href="#net_net_isipv6_input">net.isIPv6(input)</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#os_os">OS</a></span><ul>
<li><span class="stability_undefined"><a href="#os_os_eol">os.EOL</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_arch">os.arch()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_cpus">os.cpus()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_endianness">os.endianness()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_freemem">os.freemem()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_homedir">os.homedir()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_hostname">os.hostname()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_loadavg">os.loadavg()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_networkinterfaces">os.networkInterfaces()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_platform">os.platform()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_release">os.release()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_tmpdir">os.tmpdir()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_totalmem">os.totalmem()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_type">os.type()</a></span></li>
<li><span class="stability_undefined"><a href="#os_os_uptime">os.uptime()</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#path_path">Path</a></span><ul>
<li><span class="stability_undefined"><a href="#path_path_basename_p_ext">path.basename(p[, ext])</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_delimiter">path.delimiter</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_dirname_p">path.dirname(p)</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_extname_p">path.extname(p)</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_format_pathobject">path.format(pathObject)</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_isabsolute_path">path.isAbsolute(path)</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_join_path1_path2">path.join([path1][, path2][, ...])</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_normalize_p">path.normalize(p)</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_parse_pathstring">path.parse(pathString)</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_posix">path.posix</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_relative_from_to">path.relative(from, to)</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_resolve_from_to">path.resolve([from ...], to)</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_sep">path.sep</a></span></li>
<li><span class="stability_undefined"><a href="#path_path_win32">path.win32</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#process_process">Process</a></span><ul>
<li><span class="stability_undefined"><a href="#process_event_beforeexit">Event: 'beforeExit'</a></span></li>
<li><span class="stability_undefined"><a href="#process_event_exit">Event: 'exit'</a></span></li>
<li><span class="stability_undefined"><a href="#process_event_message">Event: 'message'</a></span></li>
<li><span class="stability_undefined"><a href="#process_event_rejectionhandled">Event: 'rejectionHandled'</a></span></li>
<li><span class="stability_undefined"><a href="#process_event_uncaughtexception">Event: 'uncaughtException'</a></span><ul>
<li><span class="stability_undefined"><a href="#process_warning_using_uncaughtexception_correctly">Warning: Using <code>'uncaughtException'</code> correctly</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#process_event_unhandledrejection">Event: 'unhandledRejection'</a></span></li>
<li><span class="stability_undefined"><a href="#process_exit_codes">Exit Codes</a></span></li>
<li><span class="stability_undefined"><a href="#process_signal_events">Signal Events</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_abort">process.abort()</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_arch">process.arch</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_argv">process.argv</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_chdir_directory">process.chdir(directory)</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_config">process.config</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_connected">process.connected</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_cpuusage_previousvalue">process.cpuUsage([previousValue])</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_cwd">process.cwd()</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_disconnect">process.disconnect()</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_env">process.env</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_execargv">process.execArgv</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_execpath">process.execPath</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_exit_code">process.exit([code])</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_exitcode">process.exitCode</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_getegid">process.getegid()</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_geteuid">process.geteuid()</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_getgid">process.getgid()</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_getgroups">process.getgroups()</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_getuid">process.getuid()</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_hrtime">process.hrtime()</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_initgroups_user_extra_group">process.initgroups(user, extra_group)</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_kill_pid_signal">process.kill(pid[, signal])</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_mainmodule">process.mainModule</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_memoryusage">process.memoryUsage()</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_nexttick_callback_arg">process.nextTick(callback[, arg][, ...])</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_pid">process.pid</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_platform">process.platform</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_release">process.release</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_send_message_sendhandle_callback">process.send(message[, sendHandle][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_setegid_id">process.setegid(id)</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_seteuid_id">process.seteuid(id)</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_setgid_id">process.setgid(id)</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_setgroups_groups">process.setgroups(groups)</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_setuid_id">process.setuid(id)</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_stderr">process.stderr</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_stdin">process.stdin</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_stdout">process.stdout</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_title">process.title</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_umask_mask">process.umask([mask])</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_uptime">process.uptime()</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_version">process.version</a></span></li>
<li><span class="stability_undefined"><a href="#process_process_versions">process.versions</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#punycode_punycode">Punycode</a></span><ul>
<li><span class="stability_undefined"><a href="#punycode_punycode_decode_string">punycode.decode(string)</a></span></li>
<li><span class="stability_undefined"><a href="#punycode_punycode_encode_string">punycode.encode(string)</a></span></li>
<li><span class="stability_undefined"><a href="#punycode_punycode_toascii_domain">punycode.toASCII(domain)</a></span></li>
<li><span class="stability_undefined"><a href="#punycode_punycode_tounicode_domain">punycode.toUnicode(domain)</a></span></li>
<li><span class="stability_undefined"><a href="#punycode_punycode_ucs2">punycode.ucs2</a></span><ul>
<li><span class="stability_undefined"><a href="#punycode_punycode_ucs2_decode_string">punycode.ucs2.decode(string)</a></span></li>
<li><span class="stability_undefined"><a href="#punycode_punycode_ucs2_encode_codepoints">punycode.ucs2.encode(codePoints)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#punycode_punycode_version">punycode.version</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#querystring_query_string">Query String</a></span><ul>
<li><span class="stability_undefined"><a href="#querystring_querystring_escape">querystring.escape</a></span></li>
<li><span class="stability_undefined"><a href="#querystring_querystring_parse_str_sep_eq_options">querystring.parse(str[, sep][, eq][, options])</a></span></li>
<li><span class="stability_undefined"><a href="#querystring_querystring_stringify_obj_sep_eq_options">querystring.stringify(obj[, sep][, eq][, options])</a></span></li>
<li><span class="stability_undefined"><a href="#querystring_querystring_unescape">querystring.unescape</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#readline_readline">Readline</a></span><ul>
<li><span class="stability_undefined"><a href="#readline_class_interface">Class: Interface</a></span><ul>
<li><span class="stability_undefined"><a href="#readline_rl_close">rl.close()</a></span></li>
<li><span class="stability_undefined"><a href="#readline_rl_pause">rl.pause()</a></span></li>
<li><span class="stability_undefined"><a href="#readline_rl_prompt_preservecursor">rl.prompt([preserveCursor])</a></span></li>
<li><span class="stability_undefined"><a href="#readline_rl_question_query_callback">rl.question(query, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#readline_rl_resume">rl.resume()</a></span></li>
<li><span class="stability_undefined"><a href="#readline_rl_setprompt_prompt">rl.setPrompt(prompt)</a></span></li>
<li><span class="stability_undefined"><a href="#readline_rl_write_data_key">rl.write(data[, key])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#readline_events">Events</a></span><ul>
<li><span class="stability_undefined"><a href="#readline_event_close">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#readline_event_line">Event: 'line'</a></span></li>
<li><span class="stability_undefined"><a href="#readline_event_pause">Event: 'pause'</a></span></li>
<li><span class="stability_undefined"><a href="#readline_event_resume">Event: 'resume'</a></span></li>
<li><span class="stability_undefined"><a href="#readline_event_sigcont">Event: 'SIGCONT'</a></span></li>
<li><span class="stability_undefined"><a href="#readline_event_sigint">Event: 'SIGINT'</a></span></li>
<li><span class="stability_undefined"><a href="#readline_event_sigtstp">Event: 'SIGTSTP'</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#readline_example_tiny_cli">Example: Tiny CLI</a></span></li>
<li><span class="stability_undefined"><a href="#readline_example_read_file_stream_line_by_line">Example: Read File Stream Line-by-Line</a></span></li>
<li><span class="stability_undefined"><a href="#readline_readline_clearline_stream_dir">readline.clearLine(stream, dir)</a></span></li>
<li><span class="stability_undefined"><a href="#readline_readline_clearscreendown_stream">readline.clearScreenDown(stream)</a></span></li>
<li><span class="stability_undefined"><a href="#readline_readline_createinterface_options">readline.createInterface(options)</a></span></li>
<li><span class="stability_undefined"><a href="#readline_readline_cursorto_stream_x_y">readline.cursorTo(stream, x, y)</a></span></li>
<li><span class="stability_undefined"><a href="#readline_readline_emitkeypressevents_stream_interface">readline.emitKeypressEvents(stream[, interface])</a></span></li>
<li><span class="stability_undefined"><a href="#readline_readline_movecursor_stream_dx_dy">readline.moveCursor(stream, dx, dy)</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#repl_repl">REPL</a></span><ul>
<li><span class="stability_undefined"><a href="#repl_environment_variable_options">Environment Variable Options</a></span></li>
<li><span class="stability_undefined"><a href="#repl_persistent_history">Persistent History</a></span><ul>
<li><span class="stability_0"><a href="#repl_node_repl_history_file">NODE_REPL_HISTORY_FILE</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#repl_repl_features">REPL Features</a></span><ul>
<li><span class="stability_undefined"><a href="#repl_customizing_object_displays_in_the_repl">Customizing Object displays in the REPL</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#repl_class_replserver">Class: REPLServer</a></span><ul>
<li><span class="stability_undefined"><a href="#repl_event_exit">Event: 'exit'</a></span></li>
<li><span class="stability_undefined"><a href="#repl_event_reset">Event: 'reset'</a></span></li>
<li><span class="stability_undefined"><a href="#repl_replserver_definecommand_keyword_cmd">replServer.defineCommand(keyword, cmd)</a></span></li>
<li><span class="stability_undefined"><a href="#repl_replserver_displayprompt_preservecursor">replServer.displayPrompt([preserveCursor])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#repl_repl_start_options">repl.start(options)</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#stream_stream">Stream</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_api_for_stream_consumers">API for Stream Consumers</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_class_stream_duplex">Class: stream.Duplex</a></span></li>
<li><span class="stability_undefined"><a href="#stream_class_stream_readable">Class: stream.Readable</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_event_close">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_event_data">Event: 'data'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_event_end">Event: 'end'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_event_error">Event: 'error'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_event_readable">Event: 'readable'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_ispaused">readable.isPaused()</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_pause">readable.pause()</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_pipe_destination_options">readable.pipe(destination[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_read_size">readable.read([size])</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_resume">readable.resume()</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_setencoding_encoding">readable.setEncoding(encoding)</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_unpipe_destination">readable.unpipe([destination])</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_unshift_chunk">readable.unshift(chunk)</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_wrap_stream">readable.wrap(stream)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#stream_class_stream_transform">Class: stream.Transform</a></span></li>
<li><span class="stability_undefined"><a href="#stream_class_stream_writable">Class: stream.Writable</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_event_close_1">Event: 'close'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_event_drain">Event: 'drain'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_event_error_1">Event: 'error'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_event_finish">Event: 'finish'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_event_pipe">Event: 'pipe'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_event_unpipe">Event: 'unpipe'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_writable_cork">writable.cork()</a></span></li>
<li><span class="stability_undefined"><a href="#stream_writable_end_chunk_encoding_callback">writable.end([chunk][, encoding][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#stream_writable_setdefaultencoding_encoding">writable.setDefaultEncoding(encoding)</a></span></li>
<li><span class="stability_undefined"><a href="#stream_writable_uncork">writable.uncork()</a></span></li>
<li><span class="stability_undefined"><a href="#stream_writable_write_chunk_encoding_callback">writable.write(chunk[, encoding][, callback])</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#stream_api_for_stream_implementors">API for Stream Implementors</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_class_stream_duplex_1">Class: stream.Duplex</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_new_stream_duplex_options">new stream.Duplex(options)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#stream_class_stream_passthrough">Class: stream.PassThrough</a></span></li>
<li><span class="stability_undefined"><a href="#stream_class_stream_readable_1">Class: stream.Readable</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_new_stream_readable_options">new stream.Readable([options])</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_read_size_1">readable._read(size)</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable_push_chunk_encoding">readable.push(chunk[, encoding])</a></span></li>
<li><span class="stability_undefined"><a href="#stream_example_a_counting_stream">Example: A Counting Stream</a></span></li>
<li><span class="stability_undefined"><a href="#stream_example_simpleprotocol_v1_sub_optimal">Example: SimpleProtocol v1 (Sub-optimal)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#stream_class_stream_transform_1">Class: stream.Transform</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_new_stream_transform_options">new stream.Transform([options])</a></span></li>
<li><span class="stability_undefined"><a href="#stream_events_finish_and_end">Events: 'finish' and 'end'</a></span></li>
<li><span class="stability_undefined"><a href="#stream_transform_flush_callback">transform._flush(callback)</a></span></li>
<li><span class="stability_undefined"><a href="#stream_transform_transform_chunk_encoding_callback">transform._transform(chunk, encoding, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#stream_example_simpleprotocol_parser_v2">Example: <code>SimpleProtocol</code> parser v2</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#stream_class_stream_writable_1">Class: stream.Writable</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_new_stream_writable_options">new stream.Writable([options])</a></span></li>
<li><span class="stability_undefined"><a href="#stream_writable_write_chunk_encoding_callback_1">writable._write(chunk, encoding, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#stream_writable_writev_chunks_callback">writable._writev(chunks, callback)</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#stream_simplified_constructor_api">Simplified Constructor API</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_duplex">Duplex</a></span></li>
<li><span class="stability_undefined"><a href="#stream_readable">Readable</a></span></li>
<li><span class="stability_undefined"><a href="#stream_transform">Transform</a></span></li>
<li><span class="stability_undefined"><a href="#stream_writable">Writable</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#stream_streams_under_the_hood">Streams: Under the Hood</a></span><ul>
<li><span class="stability_undefined"><a href="#stream_buffering">Buffering</a></span></li>
<li><span class="stability_undefined"><a href="#stream_compatibility_with_older_node_js_versions">Compatibility with Older Node.js Versions</a></span></li>
<li><span class="stability_undefined"><a href="#stream_object_mode">Object Mode</a></span></li>
<li><span class="stability_undefined"><a href="#stream_stream_read_0"><code>stream.read(0)</code></a></span></li>
<li><span class="stability_undefined"><a href="#stream_stream_push"><code>stream.push('')</code></a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_2"><a href="#string_decoder_string_decoder">String Decoder</a></span><ul>
<li><span class="stability_undefined"><a href="#string_decoder_class_stringdecoder">Class: StringDecoder</a></span><ul>
<li><span class="stability_undefined"><a href="#string_decoder_decoder_end">decoder.end()</a></span></li>
<li><span class="stability_undefined"><a href="#string_decoder_decoder_write_buffer">decoder.write(buffer)</a></span></li>
</ul>
</li>
</ul>
</li>
<li><span class="stability_3"><a href="#timers_timers">Timers</a></span><ul>
<li><span class="stability_undefined"><a href="#timers_clearimmediate_immediateobject">clearImmediate(immediateObject)</a></span></li>
<li><span class="stability_undefined"><a href="#timers_clearinterval_intervalobject">clearInterval(intervalObject)</a></span></li>
<li><span class="stability_undefined"><a href="#timers_cleartimeout_timeoutobject">clearTimeout(timeoutObject)</a></span></li>
<li><span class="stability_undefined"><a href="#timers_ref">ref()</a></span></li>
<li><span class="stability_undefined"><a href="#timers_setimmediate_callback_arg">setImmediate(callback[, arg][, ...])</a></span></li>
<li><span class="stability_undefined"><a href="#timers_setinterval_callback_delay_arg">setInterval(callback, delay[, arg][, ...])</a></span></li>
<li><span class="stability_undefined"><a href="#timers_settimeout_callback_delay_arg">setTimeout(callback, delay[, arg][, ...])</a></span></li>
<li><span class="stability_undefined"><a href="#timers_unref">unref()</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#tls_tls_ssl">TLS (SSL)</a></span><ul>
<li><span class="stability_undefined"><a href="#tls_client_initiated_renegotiation_attack_mitigation">Client-initiated renegotiation attack mitigation</a></span></li>
<li><span class="stability_undefined"><a href="#tls_modifying_the_default_tls_cipher_suite">Modifying the Default TLS Cipher suite</a></span></li>
<li><span class="stability_undefined"><a href="#tls_alpn_npn_and_sni">ALPN, NPN and SNI</a></span></li>
<li><span class="stability_undefined"><a href="#tls_perfect_forward_secrecy">Perfect Forward Secrecy</a></span></li>
<li><span class="stability_0"><a href="#tls_class_cryptostream">Class: CryptoStream</a></span><ul>
<li><span class="stability_undefined"><a href="#tls_cryptostream_byteswritten">cryptoStream.bytesWritten</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#tls_class_securepair">Class: SecurePair</a></span><ul>
<li><span class="stability_undefined"><a href="#tls_event_secure">Event: 'secure'</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#tls_class_tls_server">Class: tls.Server</a></span><ul>
<li><span class="stability_undefined"><a href="#tls_event_clienterror">Event: 'clientError'</a></span></li>
<li><span class="stability_undefined"><a href="#tls_event_newsession">Event: 'newSession'</a></span></li>
<li><span class="stability_undefined"><a href="#tls_event_ocsprequest">Event: 'OCSPRequest'</a></span></li>
<li><span class="stability_undefined"><a href="#tls_event_resumesession">Event: 'resumeSession'</a></span></li>
<li><span class="stability_undefined"><a href="#tls_event_secureconnection">Event: 'secureConnection'</a></span></li>
<li><span class="stability_undefined"><a href="#tls_server_addcontext_hostname_context">server.addContext(hostname, context)</a></span></li>
<li><span class="stability_undefined"><a href="#tls_server_address">server.address()</a></span></li>
<li><span class="stability_undefined"><a href="#tls_server_close_callback">server.close([callback])</a></span></li>
<li><span class="stability_undefined"><a href="#tls_server_connections">server.connections</a></span></li>
<li><span class="stability_undefined"><a href="#tls_server_getticketkeys">server.getTicketKeys()</a></span></li>
<li><span class="stability_undefined"><a href="#tls_server_listen_port_hostname_callback">server.listen(port[, hostname][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#tls_server_maxconnections">server.maxConnections</a></span></li>
<li><span class="stability_undefined"><a href="#tls_server_setticketkeys_keys">server.setTicketKeys(keys)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#tls_class_tls_tlssocket">Class: tls.TLSSocket</a></span></li>
<li><span class="stability_undefined"><a href="#tls_new_tls_tlssocket_socket_options">new tls.TLSSocket(socket[, options])</a></span><ul>
<li><span class="stability_undefined"><a href="#tls_event_ocspresponse">Event: 'OCSPResponse'</a></span></li>
<li><span class="stability_undefined"><a href="#tls_event_secureconnect">Event: 'secureConnect'</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_address">tlsSocket.address()</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_authorized">tlsSocket.authorized</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_authorizationerror">tlsSocket.authorizationError</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_encrypted">tlsSocket.encrypted</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_getcipher">tlsSocket.getCipher()</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_getpeercertificate_detailed">tlsSocket.getPeerCertificate([ detailed ])</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_getsession">tlsSocket.getSession()</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_gettlsticket">tlsSocket.getTLSTicket()</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_localport">tlsSocket.localPort</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_localaddress">tlsSocket.localAddress</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_remoteaddress">tlsSocket.remoteAddress</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_remotefamily">tlsSocket.remoteFamily</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_remoteport">tlsSocket.remotePort</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_renegotiate_options_callback">tlsSocket.renegotiate(options, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tlssocket_setmaxsendfragment_size">tlsSocket.setMaxSendFragment(size)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#tls_tls_connect_options_callback">tls.connect(options[, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tls_connect_port_host_options_callback">tls.connect(port[, host][, options][, callback])</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tls_createsecurecontext_details">tls.createSecureContext(details)</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tls_createsecurepair_context_isserver_requestcert_rejectunauthorized_options">tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tls_createserver_options_secureconnectionlistener">tls.createServer(options[, secureConnectionListener])</a></span></li>
<li><span class="stability_undefined"><a href="#tls_tls_getciphers">tls.getCiphers()</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#tty_tty">TTY</a></span><ul>
<li><span class="stability_undefined"><a href="#tty_class_readstream">Class: ReadStream</a></span><ul>
<li><span class="stability_undefined"><a href="#tty_rs_israw">rs.isRaw</a></span></li>
<li><span class="stability_undefined"><a href="#tty_rs_setrawmode_mode">rs.setRawMode(mode)</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#tty_class_writestream">Class: WriteStream</a></span><ul>
<li><span class="stability_undefined"><a href="#tty_event_resize">Event: 'resize'</a></span></li>
<li><span class="stability_undefined"><a href="#tty_ws_columns">ws.columns</a></span></li>
<li><span class="stability_undefined"><a href="#tty_ws_rows">ws.rows</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#tty_tty_isatty_fd">tty.isatty(fd)</a></span></li>
<li><span class="stability_0"><a href="#tty_tty_setrawmode_mode">tty.setRawMode(mode)</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#url_url">URL</a></span><ul>
<li><span class="stability_undefined"><a href="#url_url_parsing">URL Parsing</a></span><ul>
<li><span class="stability_undefined"><a href="#url_escaped_characters">Escaped Characters</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#url_url_format_urlobj">url.format(urlObj)</a></span></li>
<li><span class="stability_undefined"><a href="#url_url_parse_urlstr_parsequerystring_slashesdenotehost">url.parse(urlStr[, parseQueryString][, slashesDenoteHost])</a></span></li>
<li><span class="stability_undefined"><a href="#url_url_resolve_from_to">url.resolve(from, to)</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#util_util">Util</a></span><ul>
<li><span class="stability_0"><a href="#util_util_debug_string">util.debug(string)</a></span></li>
<li><span class="stability_undefined"><a href="#util_util_debuglog_section">util.debuglog(section)</a></span></li>
<li><span class="stability_undefined"><a href="#util_util_deprecate_function_string">util.deprecate(function, string)</a></span></li>
<li><span class="stability_0"><a href="#util_util_error">util.error([...])</a></span></li>
<li><span class="stability_undefined"><a href="#util_util_format_format">util.format(format[, ...])</a></span></li>
<li><span class="stability_undefined"><a href="#util_util_inherits_constructor_superconstructor">util.inherits(constructor, superConstructor)</a></span></li>
<li><span class="stability_undefined"><a href="#util_util_inspect_object_options">util.inspect(object[, options])</a></span><ul>
<li><span class="stability_undefined"><a href="#util_customizing_util_inspect_colors">Customizing <code>util.inspect</code> colors</a></span></li>
<li><span class="stability_undefined"><a href="#util_custom_inspect_function_on_objects">Custom <code>inspect()</code> function on Objects</a></span></li>
</ul>
</li>
<li><span class="stability_0"><a href="#util_util_isarray_object">util.isArray(object)</a></span></li>
<li><span class="stability_0"><a href="#util_util_isboolean_object">util.isBoolean(object)</a></span></li>
<li><span class="stability_0"><a href="#util_util_isbuffer_object">util.isBuffer(object)</a></span></li>
<li><span class="stability_0"><a href="#util_util_isdate_object">util.isDate(object)</a></span></li>
<li><span class="stability_0"><a href="#util_util_iserror_object">util.isError(object)</a></span></li>
<li><span class="stability_0"><a href="#util_util_isfunction_object">util.isFunction(object)</a></span></li>
<li><span class="stability_0"><a href="#util_util_isnull_object">util.isNull(object)</a></span></li>
<li><span class="stability_0"><a href="#util_util_isnullorundefined_object">util.isNullOrUndefined(object)</a></span></li>
<li><span class="stability_0"><a href="#util_util_isnumber_object">util.isNumber(object)</a></span></li>
<li><span class="stability_0"><a href="#util_util_isobject_object">util.isObject(object)</a></span></li>
<li><span class="stability_0"><a href="#util_util_isprimitive_object">util.isPrimitive(object)</a></span></li>
<li><span class="stability_0"><a href="#util_util_isregexp_object">util.isRegExp(object)</a></span></li>
<li><span class="stability_0"><a href="#util_util_isstring_object">util.isString(object)</a></span><ul>
<li><span class="stability_0"><a href="#util_util_issymbol_object">util.isSymbol(object)</a></span></li>
</ul>
</li>
<li><span class="stability_0"><a href="#util_util_isundefined_object">util.isUndefined(object)</a></span></li>
<li><span class="stability_undefined"><a href="#util_util_log_string">util.log(string)</a></span></li>
<li><span class="stability_0"><a href="#util_util_print">util.print([...])</a></span></li>
<li><span class="stability_0"><a href="#util_util_pump_readablestream_writablestream_callback">util.pump(readableStream, writableStream[, callback])</a></span></li>
<li><span class="stability_0"><a href="#util_util_puts">util.puts([...])</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#v8_v8">V8</a></span><ul>
<li><span class="stability_undefined"><a href="#v8_getheapstatistics">getHeapStatistics()</a></span></li>
<li><span class="stability_undefined"><a href="#v8_getheapspacestatistics">getHeapSpaceStatistics()</a></span></li>
<li><span class="stability_undefined"><a href="#v8_setflagsfromstring_string">setFlagsFromString(string)</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#vm_vm_executing_javascript">VM (Executing JavaScript)</a></span><ul>
<li><span class="stability_undefined"><a href="#vm_class_script">Class: Script</a></span><ul>
<li><span class="stability_undefined"><a href="#vm_new_vm_script_code_options">new vm.Script(code, options)</a></span></li>
<li><span class="stability_undefined"><a href="#vm_script_runincontext_contextifiedsandbox_options">script.runInContext(contextifiedSandbox[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#vm_script_runinnewcontext_sandbox_options">script.runInNewContext([sandbox][, options])</a></span></li>
<li><span class="stability_undefined"><a href="#vm_script_runinthiscontext_options">script.runInThisContext([options])</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#vm_vm_createcontext_sandbox">vm.createContext([sandbox])</a></span></li>
<li><span class="stability_undefined"><a href="#vm_vm_iscontext_sandbox">vm.isContext(sandbox)</a></span></li>
<li><span class="stability_undefined"><a href="#vm_vm_runincontext_code_contextifiedsandbox_options">vm.runInContext(code, contextifiedSandbox[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#vm_vm_runindebugcontext_code">vm.runInDebugContext(code)</a></span></li>
<li><span class="stability_undefined"><a href="#vm_vm_runinnewcontext_code_sandbox_options">vm.runInNewContext(code[, sandbox][, options])</a></span></li>
<li><span class="stability_undefined"><a href="#vm_vm_runinthiscontext_code_options">vm.runInThisContext(code[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#vm_example_run_a_server_within_a_vm">Example: Run a Server within a VM</a></span></li>
</ul>
</li>
<li><span class="stability_2"><a href="#zlib_zlib">Zlib</a></span><ul>
<li><span class="stability_undefined"><a href="#zlib_examples">Examples</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_memory_usage_tuning">Memory Usage Tuning</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_flushing">Flushing</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_constants">Constants</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_class_options">Class Options</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_class_zlib_deflate">Class: zlib.Deflate</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_class_zlib_deflateraw">Class: zlib.DeflateRaw</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_class_zlib_gunzip">Class: zlib.Gunzip</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_class_zlib_gzip">Class: zlib.Gzip</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_class_zlib_inflate">Class: zlib.Inflate</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_class_zlib_inflateraw">Class: zlib.InflateRaw</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_class_zlib_unzip">Class: zlib.Unzip</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_class_zlib_zlib">Class: zlib.Zlib</a></span><ul>
<li><span class="stability_undefined"><a href="#zlib_zlib_flush_kind_callback">zlib.flush([kind], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_params_level_strategy_callback">zlib.params(level, strategy, callback)</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_reset">zlib.reset()</a></span></li>
</ul>
</li>
<li><span class="stability_undefined"><a href="#zlib_zlib_createdeflate_options">zlib.createDeflate([options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_createdeflateraw_options">zlib.createDeflateRaw([options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_creategunzip_options">zlib.createGunzip([options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_creategzip_options">zlib.createGzip([options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_createinflate_options">zlib.createInflate([options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_createinflateraw_options">zlib.createInflateRaw([options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_createunzip_options">zlib.createUnzip([options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_convenience_methods">Convenience Methods</a></span><ul>
<li><span class="stability_undefined"><a href="#zlib_zlib_deflate_buf_options_callback">zlib.deflate(buf[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_deflatesync_buf_options">zlib.deflateSync(buf[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_deflateraw_buf_options_callback">zlib.deflateRaw(buf[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_deflaterawsync_buf_options">zlib.deflateRawSync(buf[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_gunzip_buf_options_callback">zlib.gunzip(buf[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_gunzipsync_buf_options">zlib.gunzipSync(buf[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_gzip_buf_options_callback">zlib.gzip(buf[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_gzipsync_buf_options">zlib.gzipSync(buf[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_inflate_buf_options_callback">zlib.inflate(buf[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_inflatesync_buf_options">zlib.inflateSync(buf[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_inflateraw_buf_options_callback">zlib.inflateRaw(buf[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_inflaterawsync_buf_options">zlib.inflateRawSync(buf[, options])</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_unzip_buf_options_callback">zlib.unzip(buf[, options], callback)</a></span></li>
<li><span class="stability_undefined"><a href="#zlib_zlib_unzipsync_buf_options">zlib.unzipSync(buf[, options])</a></span></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div id="apicontent">
<!-- [start-include:documentation.md] -->
<h1>About this Documentation<span><a class="mark" href="#documentation_about_this_documentation" id="documentation_about_this_documentation">#</a></span></h1>
<!-- type=misc -->
<p>The goal of this documentation is to comprehensively explain the Node.js
API, both from a reference as well as a conceptual point of view. Each
section describes a built-in module or high-level concept.</p>
<p>Where appropriate, property types, method arguments, and the arguments
provided to event handlers are detailed in a list underneath the topic
heading.</p>
<p>Every <code>.html</code> document has a corresponding <code>.json</code> document presenting
the same information in a structured manner. This feature is
experimental, and added for the benefit of IDEs and other utilities that
wish to do programmatic things with the documentation.</p>
<p>Every <code>.html</code> and <code>.json</code> file is generated based on the corresponding
<code>.md</code> file in the <code>doc/api/</code> folder in Node.js's source tree. The
documentation is generated using the <code>tools/doc/generate.js</code> program.
The HTML template is located at <code>doc/template.html</code>.</p>
<p>If you find an error in this documentation, please <a href="https://github.com/nodejs/node/issues/new">submit an issue</a>
or see <a href="https://github.com/nodejs/node/blob/master/CONTRIBUTING.md">the contributing guide</a> for directions on how to submit a patch.</p>
<h2>Stability Index<span><a class="mark" href="#documentation_stability_index" id="documentation_stability_index">#</a></span></h2>
<!--type=misc-->
<p>Throughout the documentation, you will see indications of a section's
stability. The Node.js API is still somewhat changing, and as it
matures, certain parts are more reliable than others. Some 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
and in the process of being redesigned.</p>
<p>The stability indices are as follows:</p>
<pre class="api_stability api_stability_0">Stability: 0 - Deprecated This feature is known to be problematic, and changes are planned. Do not rely on it. Use of the feature may cause warnings. Backwards compatibility should not be expected.</pre><pre class="api_stability api_stability_1">Stability: 1 - Experimental This feature is subject to change, and is gated by a command line flag. It may change or be removed in future versions.</pre><pre class="api_stability api_stability_2">Stability: 2 - Stable The API has proven satisfactory. Compatibility with the npm ecosystem is a high priority, and will not be broken unless absolutely necessary.</pre><pre class="api_stability api_stability_3">Stability: 3 - Locked Only bug fixes, security fixes, and performance improvements will be accepted. Please do not suggest API changes in this area; they will be refused.</pre><h2>JSON Output<span><a class="mark" href="#documentation_json_output" id="documentation_json_output">#</a></span></h2>
<pre class="api_stability api_stability_1">Stability: 1 - Experimental</pre><p>Every HTML file in the markdown has a corresponding JSON file with the
same data.</p>
<p>This feature was added in Node.js v0.6.12. It is experimental.</p>
<h2>Syscalls and man pages<span><a class="mark" href="#documentation_syscalls_and_man_pages" id="documentation_syscalls_and_man_pages">#</a></span></h2>
<p>System calls like <a href="http://man7.org/linux/man-pages/man2/open.2.html">open(2)</a> and <a href="http://man7.org/linux/man-pages/man2/read.2.html">read(2)</a> define the interface between user programs
and the underlying operating system. Node functions which simply wrap a syscall,
like <code>fs.open()</code>, will document that. The docs link to the corresponding man
pages (short for manual pages) which describe how the syscalls work.</p>
<p><strong>Caveat:</strong> some syscalls, like <a href="http://man7.org/linux/man-pages/man2/lchown.2.html">lchown(2)</a>, are BSD-specific. That means, for
example, that <code>fs.lchown()</code> only works on Mac OS X and other BSD-derived systems,
and is not available on Linux.</p>
<p>Most Unix syscalls have Windows equivalents, but behavior may differ on Windows
relative to Linux and OS X. For an example of the subtle ways in which it's
sometimes impossible to replace Unix syscall semantics on Windows, see <a href="https://github.com/nodejs/node/issues/4760">Node
issue 4760</a>.</p>
<!-- [end-include:documentation.md] -->
<!-- [start-include:synopsis.md] -->
<h1>Usage<span><a class="mark" href="#synopsis_usage" id="synopsis_usage">#</a></span></h1>
<!--type=misc-->
<p><code>node [options] [v8 options] [script.js | -e "script"] [arguments]</code></p>
<p>Please see the <a href="cli.html#cli_command_line_options">Command Line Options</a> document for information about
different options and ways to run scripts with Node.</p>
<h2>Example<span><a class="mark" href="#synopsis_example" id="synopsis_example">#</a></span></h2>
<p>An example of a <a href="http.html">web server</a> written with Node.js which responds with
<code>'Hello World'</code>:</p>
<pre><code class="lang-js">const http = require('http');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello World\n');
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
</code></pre>
<p>To run the server, put the code into a file called <code>example.js</code> and execute
it with Node.js:</p>
<pre><code>$ node example.js
Server running at http://127.0.0.1:3000/
</code></pre><p>All of the examples in the documentation can be run similarly.</p>
<!-- [end-include:synopsis.md] -->
<!-- [start-include:addons.md] -->
<h1>C/C++ Addons<span><a class="mark" href="#addons_c_c_addons" id="addons_c_c_addons">#</a></span></h1>
<p>Node.js Addons are dynamically-linked shared objects, written in C or C++, that
can be loaded into Node.js using the <a href="globals.html#globals_require"><code>require()</code></a> function, and used
just as if they were an ordinary Node.js module. They are used primarily to
provide an interface between JavaScript running in Node.js and C/C++ libraries.</p>
<p>At the moment, the method for implementing Addons is rather complicated,
involving knowledge of several components and APIs :</p>
<ul>
<li><p>V8: the C++ library Node.js currently uses to provide the
JavaScript implementation. V8 provides the mechanisms for creating objects,
calling functions, etc. 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), which 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 filesystem, sockets, timers and system events. libuv
also provides a pthreads-like threading abstraction that may be used to
power more sophisticated asynchronous Addons that need to move beyond the
standard event loop. Addon authors are encouraged to think about how to
avoid blocking the event loop with I/O or other time-intensive tasks by
off-loading work via libuv to non-blocking system operations, worker threads
or a custom use of libuv's threads.</p>
</li>
<li><p>Internal Node.js libraries. Node.js itself exports a number of C/C++ APIs
that Addons can use — the most important of which is the
<code>node::ObjectWrap</code> class.</p>
</li>
<li><p>Node.js includes a number of 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 V8 and OpenSSL symbols are purposefully
re-exported by Node.js and may be used to various extents by Addons.
See <a href="#linking-to-nodejs-own-dependencies">Linking to Node.js' own dependencies</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 a starting-point for your own Addon.</p>
<h2>Hello world<span><a class="mark" href="#addons_hello_world" id="addons_hello_world">#</a></span></h2>
<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="lang-js">module.exports.hello = () => 'world';
</code></pre>
<p>First, create the file <code>hello.cc</code>:</p>
<pre><code class="lang-cpp">// hello.cc
#include <node.h>
namespace demo {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
void Method(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "world"));
}
void init(Local<Object> exports) {
NODE_SET_METHOD(exports, "hello", Method);
}
NODE_MODULE(addon, init)
} // namespace demo
</code></pre>
<p>Note that all Node.js Addons must export an initialization function following
the pattern:</p>
<pre><code class="lang-cpp">void Initialize(Local<Object> exports);
NODE_MODULE(module_name, Initialize)
</code></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 .node suffix).</p>
<p>In the <code>hello.cc</code> example, then, the initialization function is <code>init</code> and the
Addon module name is <code>addon</code>.</p>
<h3>Building<span><a class="mark" href="#addons_building" id="addons_building">#</a></span></h3>
<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 your 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>{
"targets": [
{
"target_name": "addon",
"sources": [ "hello.cc" ]
}
]
}
</code></pre><p><em>Note: 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.</em></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="globals.html#globals_require"><code>require()</code></a> to the built <code>addon.node</code> module:</p>
<pre><code class="lang-js">// hello.js
const addon = require('./build/Release/addon');
console.log(addon.hello()); // 'world'
</code></pre>
<p>Please see the examples below for further information or
<a href="https://github.com/arturadib/node-qt">https://github.com/arturadib/node-qt</a> for an example in production.</p>
<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>Note that while the <code>bindings</code> package implementation is more sophisticated
in how it locates Addon modules, it is essentially using a try-catch pattern
similar to:</p>
<pre><code class="lang-js">try {
return require('./build/Release/addon.node');
} catch (err) {
return require('./build/Debug/addon.node');
}
</code></pre>
<h3>Linking to Node.js' own dependencies<span><a class="mark" href="#addons_linking_to_node_js_own_dependencies" id="addons_linking_to_node_js_own_dependencies">#</a></span></h3>
<p>Node.js uses a number of 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>
<h3>Loading Addons using require()<span><a class="mark" href="#addons_loading_addons_using_require" id="addons_loading_addons_using_require">#</a></span></h3>
<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="globals.html#globals_require"><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="globals.html#globals_require"><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="globals.html#globals_require"><code>require('addon')</code></a> will give precedence to the <code>addon.js</code> file
and load it instead.</p>
<h2>Native Abstractions for Node.js<span><a class="mark" href="#addons_native_abstractions_for_node_js" id="addons_native_abstractions_for_node_js">#</a></span></h2>
<p>Each of the examples illustrated in this document make direct use of the
Node.js and V8 APIs for implementing Addons. It is important to understand
that 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 currently 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/master/examples/">examples</a> for an
illustration of how it can be used.</p>
<h2>Addon examples<span><a class="mark" href="#addons_addon_examples" id="addons_addon_examples">#</a></span></h2>
<p>Following are some example Addons intended to help developers get started. The
examples make use of 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://developers.google.com/v8/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>{
"targets": [
{
"target_name": "addon",
"sources": [ "addon.cc" ]
}
]
}
</code></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. For example:</p>
<pre><code>"sources": ["addon.cc", "myexample.cc"]
</code></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>$ node-gyp configure build
</code></pre><h3>Function arguments<span><a class="mark" href="#addons_function_arguments" id="addons_function_arguments">#</a></span></h3>
<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="lang-cpp">// addon.cc
#include <node.h>
namespace demo {
using v8::Exception;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;
// This is the implementation of the "add" method
// Input arguments are passed using the
// const FunctionCallbackInfo<Value>& args struct
void Add(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
// Check the number of arguments passed.
if (args.Length() < 2) {
// Throw an Error that is passed back to JavaScript
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Wrong number of arguments")));
return;
}
// Check the argument types
if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
isolate->ThrowException(Exception::TypeError(
String::NewFromUtf8(isolate, "Wrong arguments")));
return;
}
// Perform the operation
double value = args[0]->NumberValue() + args[1]->NumberValue();
Local<Number> num = Number::New(isolate, value);
// Set the return value (using the passed in
// FunctionCallbackInfo<Value>&)
args.GetReturnValue().Set(num);
}
void Init(Local<Object> exports) {
NODE_SET_METHOD(exports, "add", Add);
}
NODE_MODULE(addon, Init)
} // namespace demo
</code></pre>
<p>Once compiled, the example Addon can be required and used from within Node.js:</p>
<pre><code class="lang-js">// test.js
const addon = require('./build/Release/addon');
console.log('This should be eight:', addon.add(3, 5));
</code></pre>
<h3>Callbacks<span><a class="mark" href="#addons_callbacks" id="addons_callbacks">#</a></span></h3>
<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="lang-cpp">// addon.cc
#include <node.h>
namespace demo {
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Null;
using v8::Object;
using v8::String;
using v8::Value;
void RunCallback(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
Local<Function> cb = Local<Function>::Cast(args[0]);
const unsigned argc = 1;
Local<Value> argv[argc] = { String::NewFromUtf8(isolate, "hello world") };
cb->Call(Null(isolate), argc, argv);
}
void Init(Local<Object> exports, Local<Object> module) {
NODE_SET_METHOD(module, "exports", RunCallback);
}
NODE_MODULE(addon, Init)
} // namespace demo
</code></pre>
<p>Note that 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="lang-js">// test.js
const addon = require('./build/Release/addon');
addon((msg) => {
console.log(msg); // 'hello world'
});
</code></pre>
<p>Note that, in this example, the callback function is invoked synchronously.</p>
<h3>Object factory<span><a class="mark" href="#addons_object_factory" id="addons_object_factory">#</a></span></h3>
<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="lang-cpp">// addon.cc
#include <node.h>
namespace demo {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
void CreateObject(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
Local<Object> obj = Object::New(isolate);
obj->Set(String::NewFromUtf8(isolate, "msg"), args[0]->ToString());
args.GetReturnValue().Set(obj);
}
void Init(Local<Object> exports, Local<Object> module) {
NODE_SET_METHOD(module, "exports", CreateObject);
}
NODE_MODULE(addon, Init)
} // namespace demo
</code></pre>
<p>To test it in JavaScript:</p>
<pre><code class="lang-js">// test.js
const addon = require('./build/Release/addon');
var obj1 = addon('hello');
var obj2 = addon('world');
console.log(obj1.msg, obj2.msg); // 'hello world'
</code></pre>
<h3>Function factory<span><a class="mark" href="#addons_function_factory" id="addons_function_factory">#</a></span></h3>
<p>Another common scenario is creating JavaScript functions that wrap C++
functions and returning those back to JavaScript:</p>
<pre><code class="lang-cpp">// addon.cc
#include <node.h>
namespace demo {
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
void MyFunction(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
args.GetReturnValue().Set(String::NewFromUtf8(isolate, "hello world"));
}
void CreateFunction(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, MyFunction);
Local<Function> fn = tpl->GetFunction();
// omit this to make it anonymous
fn->SetName(String::NewFromUtf8(isolate, "theFunction"));
args.GetReturnValue().Set(fn);
}
void Init(Local<Object> exports, Local<Object> module) {
NODE_SET_METHOD(module, "exports", CreateFunction);
}
NODE_MODULE(addon, Init)
} // namespace demo
</code></pre>
<p>To test:</p>
<pre><code class="lang-js">// test.js
const addon = require('./build/Release/addon');
var fn = addon();
console.log(fn()); // 'hello world'
</code></pre>
<h3>Wrapping C++ objects<span><a class="mark" href="#addons_wrapping_c_objects" id="addons_wrapping_c_objects">#</a></span></h3>
<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="lang-cpp">// addon.cc
#include <node.h>
#include "myobject.h"
namespace demo {
using v8::Local;
using v8::Object;
void InitAll(Local<Object> exports) {
MyObject::Init(exports);
}
NODE_MODULE(addon, InitAll)
} // namespace demo
</code></pre>
<p>Then, in <code>myobject.h</code>, the wrapper class inherits from <code>node::ObjectWrap</code>:</p>
<pre><code class="lang-cpp">// myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H
#include <node.h>
#include <node_object_wrap.h>
namespace demo {
class MyObject : public node::ObjectWrap {
public:
static void Init(v8::Local<v8::Object> exports);
private:
explicit MyObject(double value = 0);
~MyObject();
static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Persistent<v8::Function> constructor;
double value_;
};
} // namespace demo
#endif
</code></pre>
<p>In <code>myobject.cc</code>, implement the various methods that are to be exposed.
Below, the method <code>plusOne()</code> is exposed by adding it to the constructor's
prototype:</p>
<pre><code class="lang-cpp">// myobject.cc
#include "myobject.h"
namespace demo {
using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Value;
Persistent<Function> MyObject::constructor;
MyObject::MyObject(double value) : value_(value) {
}
MyObject::~MyObject() {
}
void MyObject::Init(Local<Object> exports) {
Isolate* isolate = exports->GetIsolate();
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);
constructor.Reset(isolate, tpl->GetFunction());
exports->Set(String::NewFromUtf8(isolate, "MyObject"),
tpl->GetFunction());
}
void MyObject::New(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if (args.IsConstructCall()) {
// Invoked as constructor: `new MyObject(...)`
double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
MyObject* obj = new MyObject(value);
obj->Wrap(args.This());
args.GetReturnValue().Set(args.This());
} else {
// Invoked as plain function `MyObject(...)`, turn into construct call.
const int argc = 1;
Local<Value> argv[argc] = { args[0] };
Local<Context> context = isolate->GetCurrentContext();
Local<Function> cons = Local<Function>::New(isolate, constructor);
Local<Object> result =
cons->NewInstance(context, argc, argv).ToLocalChecked();
args.GetReturnValue().Set(result);
}
}
void MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());
obj->value_ += 1;
args.GetReturnValue().Set(Number::New(isolate, obj->value_));
}
} // namespace demo
</code></pre>
<p>To build this example, the <code>myobject.cc</code> file must be added to the
<code>binding.gyp</code>:</p>
<pre><code>{
"targets": [
{
"target_name": "addon",
"sources": [
"addon.cc",
"myobject.cc"
]
}
]
}
</code></pre><p>Test it with:</p>
<pre><code class="lang-js">// test.js
const addon = require('./build/Release/addon');
var obj = new addon.MyObject(10);
console.log(obj.plusOne()); // 11
console.log(obj.plusOne()); // 12
console.log(obj.plusOne()); // 13
</code></pre>
<h3>Factory of wrapped objects<span><a class="mark" href="#addons_factory_of_wrapped_objects" id="addons_factory_of_wrapped_objects">#</a></span></h3>
<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="lang-js">var obj = addon.createObject();
// instead of:
// var obj = new addon.Object();
</code></pre>
<p>First, the <code>createObject()</code> method is implemented in <code>addon.cc</code>:</p>
<pre><code class="lang-cpp">// addon.cc
#include <node.h>
#include "myobject.h"
namespace demo {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::String;
using v8::Value;
void CreateObject(const FunctionCallbackInfo<Value>& args) {
MyObject::NewInstance(args);
}
void InitAll(Local<Object> exports, Local<Object> module) {
MyObject::Init(exports->GetIsolate());
NODE_SET_METHOD(module, "exports", CreateObject);
}
NODE_MODULE(addon, InitAll)
} // namespace demo
</code></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="lang-cpp">// myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H
#include <node.h>
#include <node_object_wrap.h>
namespace demo {
class MyObject : public node::ObjectWrap {
public:
static void Init(v8::Isolate* isolate);
static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);
private:
explicit MyObject(double value = 0);
~MyObject();
static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
static void PlusOne(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Persistent<v8::Function> constructor;
double value_;
};
} // namespace demo
#endif
</code></pre>
<p>The implementation in <code>myobject.cc</code> is similar to the previous example:</p>
<pre><code class="lang-cpp">// myobject.cc
#include <node.h>
#include "myobject.h"
namespace demo {
using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Value;
Persistent<Function> MyObject::constructor;
MyObject::MyObject(double value) : value_(value) {
}
MyObject::~MyObject() {
}
void MyObject::Init(Isolate* isolate) {
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
NODE_SET_PROTOTYPE_METHOD(tpl, "plusOne", PlusOne);
constructor.Reset(isolate, tpl->GetFunction());
}
void MyObject::New(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if (args.IsConstructCall()) {
// Invoked as constructor: `new MyObject(...)`
double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
MyObject* obj = new MyObject(value);
obj->Wrap(args.This());
args.GetReturnValue().Set(args.This());
} else {
// Invoked as plain function `MyObject(...)`, turn into construct call.
const int argc = 1;
Local<Value> argv[argc] = { args[0] };
Local<Function> cons = Local<Function>::New(isolate, constructor);
Local<Context> context = isolate->GetCurrentContext();
Local<Object> instance =
cons->NewInstance(context, argc, argv).ToLocalChecked();
args.GetReturnValue().Set(instance);
}
}
void MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
const unsigned argc = 1;
Local<Value> argv[argc] = { args[0] };
Local<Function> cons = Local<Function>::New(isolate, constructor);
Local<Context> context = isolate->GetCurrentContext();
Local<Object> instance =
cons->NewInstance(context, argc, argv).ToLocalChecked();
args.GetReturnValue().Set(instance);
}
void MyObject::PlusOne(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.Holder());
obj->value_ += 1;
args.GetReturnValue().Set(Number::New(isolate, obj->value_));
}
} // namespace demo
</code></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>{
"targets": [
{
"target_name": "addon",
"sources": [
"addon.cc",
"myobject.cc"
]
}
]
}
</code></pre><p>Test it with:</p>
<pre><code class="lang-js">// test.js
const createObject = require('./build/Release/addon');
var obj = createObject(10);
console.log(obj.plusOne()); // 11
console.log(obj.plusOne()); // 12
console.log(obj.plusOne()); // 13
var obj2 = createObject(20);
console.log(obj2.plusOne()); // 21
console.log(obj2.plusOne()); // 22
console.log(obj2.plusOne()); // 23
</code></pre>
<h3>Passing wrapped objects around<span><a class="mark" href="#addons_passing_wrapped_objects_around" id="addons_passing_wrapped_objects_around">#</a></span></h3>
<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="lang-cpp">// addon.cc
#include <node.h>
#include <node_object_wrap.h>
#include "myobject.h"
namespace demo {
using v8::FunctionCallbackInfo;
using v8::Isolate;
using v8::Local;
using v8::Number;
using v8::Object;
using v8::String;
using v8::Value;
void CreateObject(const FunctionCallbackInfo<Value>& args) {
MyObject::NewInstance(args);
}
void Add(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(
args[0]->ToObject());
MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(
args[1]->ToObject());
double sum = obj1->value() + obj2->value();
args.GetReturnValue().Set(Number::New(isolate, sum));
}
void InitAll(Local<Object> exports) {
MyObject::Init(exports->GetIsolate());
NODE_SET_METHOD(exports, "createObject", CreateObject);
NODE_SET_METHOD(exports, "add", Add);
}
NODE_MODULE(addon, InitAll)
} // namespace demo
</code></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="lang-cpp">// myobject.h
#ifndef MYOBJECT_H
#define MYOBJECT_H
#include <node.h>
#include <node_object_wrap.h>
namespace demo {
class MyObject : public node::ObjectWrap {
public:
static void Init(v8::Isolate* isolate);
static void NewInstance(const v8::FunctionCallbackInfo<v8::Value>& args);
inline double value() const { return value_; }
private:
explicit MyObject(double value = 0);
~MyObject();
static void New(const v8::FunctionCallbackInfo<v8::Value>& args);
static v8::Persistent<v8::Function> constructor;
double value_;
};
} // namespace demo
#endif
</code></pre>
<p>The implementation of <code>myobject.cc</code> is similar to before:</p>
<pre><code class="lang-cpp">// myobject.cc
#include <node.h>
#include "myobject.h"
namespace demo {
using v8::Context;
using v8::Function;
using v8::FunctionCallbackInfo;
using v8::FunctionTemplate;
using v8::Isolate;
using v8::Local;
using v8::Object;
using v8::Persistent;
using v8::String;
using v8::Value;
Persistent<Function> MyObject::constructor;
MyObject::MyObject(double value) : value_(value) {
}
MyObject::~MyObject() {
}
void MyObject::Init(Isolate* isolate) {
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(isolate, New);
tpl->SetClassName(String::NewFromUtf8(isolate, "MyObject"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
constructor.Reset(isolate, tpl->GetFunction());
}
void MyObject::New(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
if (args.IsConstructCall()) {
// Invoked as constructor: `new MyObject(...)`
double value = args[0]->IsUndefined() ? 0 : args[0]->NumberValue();
MyObject* obj = new MyObject(value);
obj->Wrap(args.This());
args.GetReturnValue().Set(args.This());
} else {
// Invoked as plain function `MyObject(...)`, turn into construct call.
const int argc = 1;
Local<Value> argv[argc] = { args[0] };
Local<Context> context = isolate->GetCurrentContext();
Local<Function> cons = Local<Function>::New(isolate, constructor);
Local<Object> instance =
cons->NewInstance(context, argc, argv).ToLocalChecked();
args.GetReturnValue().Set(instance);
}
}
void MyObject::NewInstance(const FunctionCallbackInfo<Value>& args) {
Isolate* isolate = args.GetIsolate();
const unsigned argc = 1;
Local<Value> argv[argc] = { args[0] };
Local<Function> cons = Local<Function>::New(isolate, constructor);
Local<Context> context = isolate->GetCurrentContext();
Local<Object> instance =
cons->NewInstance(context, argc, argv).ToLocalChecked();
args.GetReturnValue().Set(instance);
}
} // namespace demo
</code></pre>
<p>Test it with:</p>
<pre><code class="lang-js">// test.js
const addon = require('./build/Release/addon');
var obj1 = addon.createObject(10);
var obj2 = addon.createObject(20);
var result = addon.add(obj1, obj2);
console.log(result); // 30
</code></pre>
<h3>AtExit hooks<span><a class="mark" href="#addons_atexit_hooks" id="addons_atexit_hooks">#</a></span></h3>
<p>An "AtExit" hook is a function that is invoked after the Node.js event loop
has ended but before the JavaScript VM is terminated and Node.js shuts down.
"AtExit" hooks are registered using the <code>node::AtExit</code> API.</p>
<h4>void AtExit(callback, args)<span><a class="mark" href="#addons_void_atexit_callback_args" id="addons_void_atexit_callback_args">#</a></span></h4>
<div class="signature"><ul>
<li><code>callback</code>: <code>void (*)(void*)</code> - A pointer to the function to call at exit.</li>
<li><code>args</code>: <code>void*</code> - A pointer to pass to the callback at exit.</li>
</ul>
</div><p>Registers exit hooks that run after the event loop has ended but before the VM
is killed.</p>
<p>AtExit takes two parameters: a pointer to a callback function to run at exit,
and a pointer to untyped context data to be passed to that callback.</p>
<p>Callbacks are run in last-in first-out order.</p>
<p>The following <code>addon.cc</code> implements AtExit:</p>
<pre><code class="lang-cpp">// addon.cc
#undef NDEBUG
#include <assert.h>
#include <stdlib.h>
#include <node.h>
namespace demo {
using node::AtExit;
using v8::HandleScope;
using v8::Isolate;
using v8::Local;
using v8::Object;
static char cookie[] = "yum yum";
static int at_exit_cb1_called = 0;
static int at_exit_cb2_called = 0;
static void at_exit_cb1(void* arg) {
Isolate* isolate = static_cast<Isolate*>(arg);
HandleScope scope(isolate);
Local<Object> obj = Object::New(isolate);
assert(!obj.IsEmpty()); // assert VM is still alive
assert(obj->IsObject());
at_exit_cb1_called++;
}
static void at_exit_cb2(void* arg) {
assert(arg == static_cast<void*>(cookie));
at_exit_cb2_called++;
}
static void sanity_check(void*) {
assert(at_exit_cb1_called == 1);
assert(at_exit_cb2_called == 2);
}
void init(Local<Object> exports) {
AtExit(sanity_check);
AtExit(at_exit_cb2, cookie);
AtExit(at_exit_cb2, cookie);
AtExit(at_exit_cb1, exports->GetIsolate());
}
NODE_MODULE(addon, init);
} // namespace demo
</code></pre>
<p>Test in JavaScript by running:</p>
<pre><code class="lang-js">// test.js
const addon = require('./build/Release/addon');
</code></pre>
<!-- [end-include:addons.md] -->
<!-- [start-include:assert.md] -->
<h1>Assert<span><a class="mark" href="#assert_assert" id="assert_assert">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>The <code>assert</code> module provides a simple set of assertion tests that can be used to
test invariants.</p>
<h2>assert(value[, message])<span><a class="mark" href="#assert_assert_value_message" id="assert_assert_value_message">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.9</span>
</div><ul>
<li><code>value</code> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span></li>
</ul>
<p>An alias of <a href="#assert_assert_ok_value_message"><code>assert.ok()</code></a> .</p>
<pre><code class="lang-js">const assert = require('assert');
assert(true); // OK
assert(1); // OK
assert(false);
// throws "AssertionError: false == true"
assert(0);
// throws "AssertionError: 0 == true"
assert(false, 'it\'s false');
// throws "AssertionError: it's false"
</code></pre>
<h2>assert.deepEqual(actual, expected[, message])<span><a class="mark" href="#assert_assert_deepequal_actual_expected_message" id="assert_assert_deepequal_actual_expected_message">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><ul>
<li><code>actual</code> <span class="type"><any></span></li>
<li><code>expected</code> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span></li>
</ul>
<p>Tests for deep equality between the <code>actual</code> and <code>expected</code> parameters.
Primitive values are compared with the equal comparison operator ( <code>==</code> ).</p>
<p>Only enumerable "own" properties are considered. The <code>deepEqual()</code>
implementation does not test object prototypes, attached symbols, or
non-enumerable properties. This can lead to some potentially surprising
results. For example, the following example does not throw an <code>AssertionError</code>
because the properties on the <a href="errors.html#errors_class_error"><code>Error</code></a> object are non-enumerable:</p>
<pre><code class="lang-js">// WARNING: This does not throw an AssertionError!
assert.deepEqual(Error('a'), Error('b'));
</code></pre>
<p>"Deep" equality means that the enumerable "own" properties of child objects
are evaluated also:</p>
<pre><code class="lang-js">const assert = require('assert');
const obj1 = {
a : {
b : 1
}
};
const obj2 = {
a : {
b : 2
}
};
const obj3 = {
a : {
b : 1
}
}
const obj4 = Object.create(obj1);
assert.deepEqual(obj1, obj1);
// OK, object is equal to itself
assert.deepEqual(obj1, obj2);
// AssertionError: { a: { b: 1 } } deepEqual { a: { b: 2 } }
// values of b are different
assert.deepEqual(obj1, obj3);
// OK, objects are equal
assert.deepEqual(obj1, obj4);
// AssertionError: { a: { b: 1 } } deepEqual {}
// Prototypes are ignored
</code></pre>
<p>If the values are not equal, an <code>AssertionError</code> 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.</p>
<h2>assert.deepStrictEqual(actual, expected[, message])<span><a class="mark" href="#assert_assert_deepstrictequal_actual_expected_message" id="assert_assert_deepstrictequal_actual_expected_message">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v1.2.0</span>
</div><ul>
<li><code>actual</code> <span class="type"><any></span></li>
<li><code>expected</code> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span></li>
</ul>
<p>Generally identical to <code>assert.deepEqual()</code> with two exceptions. First,
primitive values are compared using the strict equality operator ( <code>===</code> ).
Second, object comparisons include a strict equality check of their prototypes.</p>
<pre><code class="lang-js">const assert = require('assert');
assert.deepEqual({a:1}, {a:'1'});
// OK, because 1 == '1'
assert.deepStrictEqual({a:1}, {a:'1'});
// AssertionError: { a: 1 } deepStrictEqual { a: '1' }
// because 1 !== '1' using strict equality
</code></pre>
<p>If the values are not equal, an <code>AssertionError</code> 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.</p>
<h2>assert.doesNotThrow(block[, error][, message])<span><a class="mark" href="#assert_assert_doesnotthrow_block_error_message" id="assert_assert_doesnotthrow_block_error_message">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><ul>
<li><code>block</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> <span class="type"><any></span></li>
</ul>
<p>Asserts that the function <code>block</code> does not throw an error. See
<a href="#assert_assert_throws_block_error_message"><code>assert.throws()</code></a> for more details.</p>
<p>When <code>assert.doesNotThrow()</code> is called, it will immediately call the <code>block</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 <code>AssertionError</code> 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>The following, for instance, will throw the <a href="errors.html#errors_class_typeerror"><code>TypeError</code></a> because there is no
matching error type in the assertion:</p>
<pre><code class="lang-js">assert.doesNotThrow(
() => {
throw new TypeError('Wrong value');
},
SyntaxError
);
</code></pre>
<p>However, the following will result in an <code>AssertionError</code> with the message
'Got unwanted exception (TypeError)..':</p>
<pre><code class="lang-js">assert.doesNotThrow(
() => {
throw new TypeError('Wrong value');
},
TypeError
);
</code></pre>
<p>If an <code>AssertionError</code> is thrown and a value is provided for the <code>message</code>
parameter, the value of <code>message</code> will be appended to the <code>AssertionError</code>
message:</p>
<pre><code class="lang-js">assert.doesNotThrow(
() => {
throw new TypeError('Wrong value');
},
TypeError,
'Whoops'
);
// Throws: AssertionError: Got unwanted exception (TypeError). Whoops
</code></pre>
<h2>assert.equal(actual, expected[, message])<span><a class="mark" href="#assert_assert_equal_actual_expected_message" id="assert_assert_equal_actual_expected_message">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><ul>
<li><code>actual</code> <span class="type"><any></span></li>
<li><code>expected</code> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span></li>
</ul>
<p>Tests shallow, coercive equality between the <code>actual</code> and <code>expected</code> parameters
using the equal comparison operator ( <code>==</code> ).</p>
<pre><code class="lang-js">const assert = require('assert');
assert.equal(1, 1);
// OK, 1 == 1
assert.equal(1, '1');
// OK, 1 == '1'
assert.equal(1, 2);
// AssertionError: 1 == 2
assert.equal({a: {b: 1}}, {a: {b: 1}});
//AssertionError: { a: { b: 1 } } == { a: { b: 1 } }
</code></pre>
<p>If the values are not equal, an <code>AssertionError</code> 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.</p>
<h2>assert.fail(actual, expected, message, operator)<span><a class="mark" href="#assert_assert_fail_actual_expected_message_operator" id="assert_assert_fail_actual_expected_message_operator">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><ul>
<li><code>actual</code> <span class="type"><any></span></li>
<li><code>expected</code> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span></li>
<li><code>operator</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a></li>
</ul>
<p>Throws an <code>AssertionError</code>. 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>.
Otherwise, the error message is the value of <code>message</code>.</p>
<pre><code class="lang-js">const assert = require('assert');
assert.fail(1, 2, undefined, '>');
// AssertionError: 1 > 2
assert.fail(1, 2, 'whoops', '>');
// AssertionError: whoops
</code></pre>
<h2>assert.ifError(value)<span><a class="mark" href="#assert_assert_iferror_value" id="assert_assert_iferror_value">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.97</span>
</div><ul>
<li><code>value</code> <span class="type"><any></span></li>
</ul>
<p>Throws <code>value</code> if <code>value</code> is truthy. This is useful when testing the <code>error</code>
argument in callbacks.</p>
<pre><code class="lang-js">const assert = require('assert');
assert.ifError(0); // OK
assert.ifError(1); // Throws 1
assert.ifError('error') // Throws 'error'
assert.ifError(new Error()); // Throws Error
</code></pre>
<h2>assert.notDeepEqual(actual, expected[, message])<span><a class="mark" href="#assert_assert_notdeepequal_actual_expected_message" id="assert_assert_notdeepequal_actual_expected_message">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><ul>
<li><code>actual</code> <span class="type"><any></span></li>
<li><code>expected</code> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span></li>
</ul>
<p>Tests for any deep inequality. Opposite of <a href="#assert_assert_deepequal_actual_expected_message"><code>assert.deepEqual()</code></a>.</p>
<pre><code class="lang-js">const assert = require('assert');
const obj1 = {
a : {
b : 1
}
};
const obj2 = {
a : {
b : 2
}
};
const obj3 = {
a : {
b : 1
}
};
const obj4 = Object.create(obj1);
assert.notDeepEqual(obj1, obj1);
// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
assert.notDeepEqual(obj1, obj2);
// OK, obj1 and obj2 are not deeply equal
assert.notDeepEqual(obj1, obj3);
// AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
assert.notDeepEqual(obj1, obj4);
// OK, obj1 and obj4 are not deeply equal
</code></pre>
<p>If the values are deeply equal, an <code>AssertionError</code> 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.</p>
<h2>assert.notDeepStrictEqual(actual, expected[, message])<span><a class="mark" href="#assert_assert_notdeepstrictequal_actual_expected_message" id="assert_assert_notdeepstrictequal_actual_expected_message">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v1.2.0</span>
</div><ul>
<li><code>actual</code> <span class="type"><any></span></li>
<li><code>expected</code> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span></li>
</ul>
<p>Tests for deep strict inequality. Opposite of <a href="#assert_assert_deepstrictequal_actual_expected_message"><code>assert.deepStrictEqual()</code></a>.</p>
<pre><code class="lang-js">const assert = require('assert');
assert.notDeepEqual({a:1}, {a:'1'});
// AssertionError: { a: 1 } notDeepEqual { a: '1' }
assert.notDeepStrictEqual({a:1}, {a:'1'});
// OK
</code></pre>
<p>If the values are deeply and strictly equal, an <code>AssertionError</code> 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.</p>
<h2>assert.notEqual(actual, expected[, message])<span><a class="mark" href="#assert_assert_notequal_actual_expected_message" id="assert_assert_notequal_actual_expected_message">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><ul>
<li><code>actual</code> <span class="type"><any></span></li>
<li><code>expected</code> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span></li>
</ul>
<p>Tests shallow, coercive inequality with the not equal comparison operator
( <code>!=</code> ).</p>
<pre><code class="lang-js">const assert = require('assert');
assert.notEqual(1, 2);
// OK
assert.notEqual(1, 1);
// AssertionError: 1 != 1
assert.notEqual(1, '1');
// AssertionError: 1 != '1'
</code></pre>
<p>If the values are equal, an <code>AssertionError</code> 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.</p>
<h2>assert.notStrictEqual(actual, expected[, message])<span><a class="mark" href="#assert_assert_notstrictequal_actual_expected_message" id="assert_assert_notstrictequal_actual_expected_message">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><ul>
<li><code>actual</code> <span class="type"><any></span></li>
<li><code>expected</code> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span></li>
</ul>
<p>Tests strict inequality as determined by the strict not equal operator
( <code>!==</code> ).</p>
<pre><code class="lang-js">const assert = require('assert');
assert.notStrictEqual(1, 2);
// OK
assert.notStrictEqual(1, 1);
// AssertionError: 1 !== 1
assert.notStrictEqual(1, '1');
// OK
</code></pre>
<p>If the values are strictly equal, an <code>AssertionError</code> 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.</p>
<h2>assert.ok(value[, message])<span><a class="mark" href="#assert_assert_ok_value_message" id="assert_assert_ok_value_message">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><ul>
<li><code>value</code> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span></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 <code>AssertionError</code> 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.</p>
<pre><code class="lang-js">const assert = require('assert');
assert.ok(true); // OK
assert.ok(1); // OK
assert.ok(false);
// throws "AssertionError: false == true"
assert.ok(0);
// throws "AssertionError: 0 == true"
assert.ok(false, 'it\'s false');
// throws "AssertionError: it's false"
</code></pre>
<h2>assert.strictEqual(actual, expected[, message])<span><a class="mark" href="#assert_assert_strictequal_actual_expected_message" id="assert_assert_strictequal_actual_expected_message">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><ul>
<li><code>actual</code> <span class="type"><any></span></li>
<li><code>expected</code> <span class="type"><any></span></li>
<li><code>message</code> <span class="type"><any></span></li>
</ul>
<p>Tests strict equality as determined by the strict equality operator ( <code>===</code> ).</p>
<pre><code class="lang-js">const assert = require('assert');
assert.strictEqual(1, 2);
// AssertionError: 1 === 2
assert.strictEqual(1, 1);
// OK
assert.strictEqual(1, '1');
// AssertionError: 1 === '1'
</code></pre>
<p>If the values are not strictly equal, an <code>AssertionError</code> 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.</p>
<h2>assert.throws(block[, error][, message])<span><a class="mark" href="#assert_assert_throws_block_error_message" id="assert_assert_throws_block_error_message">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><ul>
<li><code>block</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> <span class="type"><any></span></li>
</ul>
<p>Expects the function <code>block</code> to throw an error.</p>
<p>If specified, <code>error</code> can be a constructor, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions"><code>RegExp</code></a>, or validation
function.</p>
<p>If specified, <code>message</code> will be the message provided by the <code>AssertionError</code> if
the block fails to throw.</p>
<p>Validate instanceof using constructor:</p>
<pre><code class="lang-js">assert.throws(
() => {
throw new Error('Wrong value');
},
Error
);
</code></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>
<pre><code class="lang-js">assert.throws(
() => {
throw new Error('Wrong value');
},
/value/
);
</code></pre>
<p>Custom error validation:</p>
<pre><code class="lang-js">assert.throws(
() => {
throw new Error('Wrong value');
},
function(err) {
if ( (err instanceof Error) && /value/.test(err) ) {
return true;
}
},
'unexpected error'
);
</code></pre>
<p>Note that <code>error</code> can not 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:</p>
<pre><code class="lang-js">// THIS IS A MISTAKE! DO NOT DO THIS!
assert.throws(myFunction, 'missing foo', 'did not throw with expected message');
// Do this instead.
assert.throws(myFunction, /missing foo/, 'did not throw with expected message');
</code></pre>
<!-- [end-include:assert.md] -->
<!-- [start-include:buffer.md] -->
<h1>Buffer<span><a class="mark" href="#buffer_buffer" id="buffer_buffer">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>Prior to the introduction of <code>TypedArray</code> in ECMAScript 2015 (ES6), the
JavaScript language had no mechanism for reading or manipulating streams
of binary data. The <code>Buffer</code> class was introduced as part of the Node.js
API to make it possible to interact with octet streams in the context of things
like TCP streams and file system operations.</p>
<p>Now that <code>TypedArray</code> has been added in ES6, the <code>Buffer</code> class implements the
<code>Uint8Array</code> API in a manner that is more optimized and suitable for Node.js'
use cases.</p>
<p>Instances of the <code>Buffer</code> class are similar to arrays of integers but
correspond to fixed-sized, raw memory allocations outside the V8 heap.
The size of the <code>Buffer</code> is established when it is created and cannot be
resized.</p>
<p>The <code>Buffer</code> class is a global within Node.js, making it unlikely that one
would need to ever use <code>require('buffer').Buffer</code>.</p>
<pre><code class="lang-js">const buf1 = new Buffer(10);
// creates a buffer of length 10
// This is the same as Buffer.allocUnsafe(10), and the returned
// Buffer instance might contain old data that needs to be
// overwritten using either fill() or write().
const buf2 = new Buffer([1,2,3]);
// creates a buffer containing [01, 02, 03]
// This is the same as Buffer.from([1,2,3]).
const buf3 = new Buffer('test');
// creates a buffer containing ASCII bytes [74, 65, 73, 74]
// This is the same as Buffer.from('test').
const buf4 = new Buffer('tést', 'utf8');
// creates a buffer containing UTF8 bytes [74, c3, a9, 73, 74]
// This is the same as Buffer.from('tést', 'utf8').
const buf5 = Buffer.alloc(10);
// Creates a zero-filled Buffer of length 10.
const buf6 = Buffer.alloc(10, 1);
// Creates a Buffer of length 10, filled with 0x01.
const buf7 = Buffer.allocUnsafe(10);
// Creates an uninitialized buffer of length 10.
// This is faster than calling Buffer.alloc() but the returned
// Buffer instance might contain old data that needs to be
// overwritten using either fill() or write().
const buf8 = Buffer.from([1,2,3]);
// Creates a Buffer containing [01, 02, 03].
const buf9 = Buffer.from('test');
// Creates a Buffer containing ASCII bytes [74, 65, 73, 74].
const buf8 = Buffer.from('tést', 'utf8');
// Creates a Buffer containing UTF8 bytes [74, c3, a9, 73, 74].
</code></pre>
<h2><code>Buffer.from()</code>, <code>Buffer.alloc()</code>, and <code>Buffer.allocUnsafe()</code><span><a class="mark" href="#buffer_buffer_from_buffer_alloc_and_buffer_allocunsafe" id="buffer_buffer_from_buffer_alloc_and_buffer_allocunsafe">#</a></span></h2>
<p>Historically, <code>Buffer</code> instances have been 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. 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> objects <em>must</em> be initialized <em>manually</em> by using either
<a href="#buffer_buf_fill_value_offset_end"><code>buf.fill(0)</code></a> or by writing to the <code>Buffer</code> completely. 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>.</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 <code>ArrayBuffer</code> returns a <code>Buffer</code> that shares allocated memory with
the given <code>ArrayBuffer</code>.</li>
</ul>
<p>Because the behavior of <code>new Buffer()</code> changes significantly based on the type
of value passed as the first argument, applications that do not properly
validate the input arguments passed to <code>new Buffer()</code>, or that fail to
appropriately initialize newly allocated <code>Buffer</code> content, can inadvertently
introduce security and reliability issues into their code.</p>
<p>To make the creation of <code>Buffer</code> objects more reliable and less error prone,
new <code>Buffer.from()</code>, <code>Buffer.alloc()</code>, and <code>Buffer.allocUnsafe()</code> methods have
been introduced as an alternative means of creating <code>Buffer</code> instances.</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="#buffer_class_method_buffer_from_array"><code>Buffer.from(array)</code></a> returns a new <code>Buffer</code> containing
a <em>copy</em> of the provided octets.</li>
<li><a href="#buffer_class_method_buffer_from_arraybuffer"><code>Buffer.from(arrayBuffer)</code></a> returns a new <code>Buffer</code>
that <em>shares</em> the same allocated memory as the given <code>ArrayBuffer</code>.</li>
<li><a href="#buffer_class_method_buffer_from_buffer"><code>Buffer.from(buffer)</code></a> returns a new <code>Buffer</code>
containing a <em>copy</em> of the contents of the given <code>Buffer</code>.</li>
<li><a href="#buffer_class_method_buffer_from_str_encoding"><code>Buffer.from(str[, encoding])</code></a> returns a new <code>Buffer</code>
containing a <em>copy</em> of the provided string.</li>
<li><a href="#buffer_class_method_buffer_alloc_size_fill_encoding"><code>Buffer.alloc(size[, fill[, encoding]])</code></a> returns a "filled"
<code>Buffer</code> instance of the specified size. This method can be significantly
slower than <a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe(size)</code></a> but ensures
that newly created <code>Buffer</code> instances never contain old and potentially
sensitive data.</li>
<li><a href="#buffer_class_method_buffer_allocunsafe_size"><code>Buffer.allocUnsafe(size)</code></a> and
<a href="#buffer_class_method_buffer_allocunsafeslow_size"><code>Buffer.allocUnsafeSlow(size)</code></a> each return a
new <code>Buffer</code> of the specified <code>size</code> whose content <em>must</em> be initialized
using either <a href="#buffer_buf_fill_value_offset_end"><code>buf.fill(0)</code></a> or written to completely.</li>
</ul>
<p><code>Buffer</code> instances returned by <code>Buffer.allocUnsafe(size)</code> <em>may</em> be allocated
off a shared internal memory pool if <code>size</code> is less than or equal to half
<code>Buffer.poolSize</code>. Instances returned by <code>Buffer.allocUnsafeSlow(size)</code> <em>never</em>
use the shared internal memory pool.</p>
<h3>What makes <code>Buffer.allocUnsafe(size)</code> and <code>Buffer.allocUnsafeSlow(size)</code> "unsafe"?<span><a class="mark" href="#buffer_what_makes_buffer_allocunsafe_size_and_buffer_allocunsafeslow_size_unsafe" id="buffer_what_makes_buffer_allocunsafe_size_and_buffer_allocunsafeslow_size_unsafe">#</a></span></h3>
<p>When calling <code>Buffer.allocUnsafe()</code> (and <code>Buffer.allocUnsafeSlow()</code>), 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 <code>Buffer.allocUnsafe()</code> 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 <code>Buffer.allocUnsafe()</code>,
extra care <em>must</em> be taken in order to avoid introducing security
vulnerabilities into an application.</p>
<h2>Buffers and Character Encodings<span><a class="mark" href="#buffer_buffers_and_character_encodings" id="buffer_buffers_and_character_encodings">#</a></span></h2>
<p>Buffers are commonly used to represent sequences of encoded characters
such as UTF8, UCS2, Base64 or even Hex-encoded data. It is possible to
convert back and forth between Buffers and ordinary JavaScript string objects
by using an explicit encoding method.</p>
<pre><code class="lang-js">const buf = new Buffer('hello world', 'ascii');
console.log(buf.toString('hex'));
// prints: 68656c6c6f20776f726c64
console.log(buf.toString('base64'));
// prints: aGVsbG8gd29ybGQ=
</code></pre>
<p>The character encodings currently supported by Node.js include:</p>
<ul>
<li><p><code>'ascii'</code> - for 7-bit ASCII data only. This encoding method is very fast and
will strip the high bit if set.</p>
</li>
<li><p><code>'utf8'</code> - Multibyte encoded Unicode characters. Many web pages and other
document formats use UTF-8.</p>
</li>
<li><p><code>'utf16le'</code> - 2 or 4 bytes, little-endian encoded Unicode characters.
Surrogate pairs (U+10000 to U+10FFFF) are supported.</p>
</li>
<li><p><code>'ucs2'</code> - Alias of <code>'utf16le'</code>.</p>
</li>
<li><p><code>'base64'</code> - Base64 string encoding. When creating a buffer 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>.</p>
</li>
<li><p><code>'binary'</code> - A way of encoding the buffer into a one-byte (<code>latin-1</code>)
encoded string. The string <code>'latin-1'</code> is not supported. Instead, pass
<code>'binary'</code> to use <code>'latin-1'</code> encoding.</p>
</li>
<li><p><code>'hex'</code> - Encode each byte as two hexadecimal characters.</p>
</li>
</ul>
<h2>Buffers and TypedArray<span><a class="mark" href="#buffer_buffers_and_typedarray" id="buffer_buffers_and_typedarray">#</a></span></h2>
<p>Buffers are also <code>Uint8Array</code> TypedArray instances. However, there are subtle
incompatibilities with the TypedArray specification in ECMAScript 2015. For
instance, while <code>ArrayBuffer#slice()</code> creates a copy of the slice,
the implementation of <a href="#buffer_buf_slice_start_end"><code>Buffer#slice()</code></a> creates a view over the
existing Buffer without copying, making <code>Buffer#slice()</code> far more efficient.</p>
<p>It is also possible to create new TypedArray instances from a <code>Buffer</code> with the
following caveats:</p>
<ol>
<li><p>The Buffer instances's memory is copied to the TypedArray, not shared.</p>
</li>
<li><p>The Buffer's memory is interpreted as an array of distinct elements, and not
as a byte array of the target type. That is,
<code>new Uint32Array(new Buffer([1,2,3,4]))</code> creates a 4-element <code>Uint32Array</code>
with elements <code>[1,2,3,4]</code>, not a <code>Uint32Array</code> with a single element
<code>[0x1020304]</code> or <code>[0x4030201]</code>.</p>
</li>
</ol>
<p>It is possible to create a new Buffer that shares the same allocated memory as
a TypedArray instance by using the TypeArray objects <code>.buffer</code> property:</p>
<pre><code class="lang-js">const arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
const buf1 = new Buffer(arr); // copies the buffer
const buf2 = new Buffer(arr.buffer); // shares the memory with arr;
console.log(buf1);
// Prints: <Buffer 88 a0>, copied buffer has only two elements
console.log(buf2);
// Prints: <Buffer 88 13 a0 0f>
arr[1] = 6000;
console.log(buf1);
// Prints: <Buffer 88 a0>
console.log(buf2);
// Prints: <Buffer 88 13 70 17>
</code></pre>
<p>Note that when creating a Buffer using the TypeArray's <code>.buffer</code>, it is not
currently possible to use only a portion of the underlying <code>ArrayBuffer</code>. To
create a Buffer that uses only a part of the <code>ArrayBuffer</code>, use the
<a href="#buffer_buf_slice_start_end"><code>buf.slice()</code></a> function after the Buffer is created:</p>
<pre><code class="lang-js">const arr = new Uint16Array(20);
const buf = new Buffer(arr.buffer).slice(0, 16);
console.log(buf.length);
// Prints: 16
</code></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> (e.g.<code>Uint8Array.from()</code>) have
different signatures and implementations. Specifically, the TypedArray 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="#buffer_class_method_buffer_from_array"><code>Buffer.from(array)</code></a></li>
<li><a href="#buffer_class_method_buffer_from_buffer"><code>Buffer.from(buffer)</code></a></li>
<li><a href="#buffer_class_method_buffer_from_arraybuffer"><code>Buffer.from(arrayBuffer)</code></a></li>
<li><a href="#buffer_class_method_buffer_from_str_encoding"><code>Buffer.from(str[, encoding])</code></a></li>
</ul>
<h2>Buffers and ES6 iteration<span><a class="mark" href="#buffer_buffers_and_es6_iteration" id="buffer_buffers_and_es6_iteration">#</a></span></h2>
<p>Buffers can be iterated over using the ECMAScript 2015 (ES6) <code>for..of</code> syntax:</p>
<pre><code class="lang-js">const buf = new Buffer([1, 2, 3]);
for (var b of buf)
console.log(b)
// Prints:
// 1
// 2
// 3
</code></pre>
<p>Additionally, the <a href="#buffer_buf_values"><code>buf.values()</code></a>, <a href="#buffer_buf_keys"><code>buf.keys()</code></a>, and
<a href="#buffer_buf_entries"><code>buf.entries()</code></a> methods can be used to create iterators.</p>
<h2>The <code>--zero-fill-buffers</code> command line option<span><a class="mark" href="#buffer_the_zero_fill_buffers_command_line_option" id="buffer_the_zero_fill_buffers_command_line_option">#</a></span></h2>
<p>Node.js can be started using the <code>--zero-fill-buffers</code> command line option to
force all newly allocated <code>Buffer</code> and <code>SlowBuffer</code> instances created using
either <code>new Buffer(size)</code> and <code>new SlowBuffer(size)</code> to be <em>automatically
zero-filled</em> upon creation. Use of this flag <em>changes the default behavior</em> of
these methods and <em>can have a significant impact</em> on performance. Use of the
<code>--zero-fill-buffers</code> option is recommended only when absolutely necessary to
enforce that newly allocated <code>Buffer</code> instances cannot contain potentially
sensitive data.</p>
<pre><code>$ node --zero-fill-buffers
> Buffer(5);
<Buffer 00 00 00 00 00>
</code></pre><h2>Class: Buffer<span><a class="mark" href="#buffer_class_buffer" id="buffer_class_buffer">#</a></span></h2>
<p>The Buffer class is a global type for dealing with binary data directly.
It can be constructed in a variety of ways.</p>
<h3>new Buffer(array)<span><a class="mark" href="#buffer_new_buffer_array" id="buffer_new_buffer_array">#</a></span></h3>
<div class="signature"><ul>
<li><code>array</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
</div><p>Allocates a new Buffer using an <code>array</code> of octets.</p>
<pre><code class="lang-js">const buf = new Buffer([0x62,0x75,0x66,0x66,0x65,0x72]);
// creates a new Buffer containing ASCII bytes
// ['b','u','f','f','e','r']
</code></pre>
<h3>new Buffer(buffer)<span><a class="mark" href="#buffer_new_buffer_buffer" id="buffer_new_buffer_buffer">#</a></span></h3>
<div class="signature"><ul>
<li><code>buffer</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li>
</ul>
</div><p>Copies the passed <code>buffer</code> data onto a new <code>Buffer</code> instance.</p>
<pre><code class="lang-js">const buf1 = new Buffer('buffer');
const buf2 = new Buffer(buf1);
buf1[0] = 0x61;
console.log(buf1.toString());
// 'auffer'
console.log(buf2.toString());
// 'buffer' (copy is not changed)
</code></pre>
<h3>new Buffer(arrayBuffer)<span><a class="mark" href="#buffer_new_buffer_arraybuffer" id="buffer_new_buffer_arraybuffer">#</a></span></h3>
<div class="signature"><ul>
<li><code>arrayBuffer</code> - The <code>.buffer</code> property of a <code>TypedArray</code> or a <code>new
ArrayBuffer()</code></li>
</ul>
</div><p>When passed a reference to the <code>.buffer</code> property of a <code>TypedArray</code> instance,
the newly created Buffer will share the same allocated memory as the
TypedArray.</p>
<pre><code class="lang-js">const arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
const buf = new Buffer(arr.buffer); // shares the memory with arr;
console.log(buf);
// Prints: <Buffer 88 13 a0 0f>
// changing the TypdArray changes the Buffer also
arr[1] = 6000;
console.log(buf);
// Prints: <Buffer 88 13 70 17>
</code></pre>
<h3>new Buffer(size)<span><a class="mark" href="#buffer_new_buffer_size" id="buffer_new_buffer_size">#</a></span></h3>
<div class="signature"><ul>
<li><code>size</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a></li>
</ul>
</div><p>Allocates a new Buffer of <code>size</code> bytes. The <code>size</code> must be less than
or equal to the value of <code>require('buffer').kMaxLength</code> (on 64-bit
architectures, <code>kMaxLength</code> is <code>(2^31)-1</code>). Otherwise, a <a href="errors.html#errors_class_rangeerror"><code>RangeError</code></a> is
thrown. If a <code>size</code> less than 0 is specified, a zero-length Buffer will be
created.</p>
<p>Unlike <code>ArrayBuffers</code>, the underlying memory for Buffer instances created in
this way is not initialized. The contents of a newly created <code>Buffer</code> are
unknown and could contain sensitive data. Use <a href="#buffer_buf_fill_value_offset_end"><code>buf.fill(0)</code></a> to initialize a
Buffer to zeroes.</p>
<pre><code class="lang-js">const buf = new Buffer(5);
console.log(buf);
// <Buffer 78 e0 82 02 01>
// (octets will be different, every time)
buf.fill(0);
console.log(buf);
// <Buffer 00 00 00 00 00>
</code></pre>
<h3>new Buffer(str[, encoding])<span><a class="mark" href="#buffer_new_buffer_str_encoding" id="buffer_new_buffer_str_encoding">#</a></span></h3>
<div class="signature"><ul>
<li><code>str</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> Default: <code>'utf8'</code></li>
</ul>
</div><p>Creates a new Buffer containing the given JavaScript string <code>str</code>. If
provided, the <code>encoding</code> parameter identifies the strings character encoding.</p>
<pre><code class="lang-js">const buf1 = new Buffer('this is a tést');
console.log(buf1.toString());
// prints: this is a tést
console.log(buf1.toString('ascii'));
// prints: this is a tC)st
const buf2 = new Buffer('7468697320697320612074c3a97374', 'hex');
console.log(buf2.toString());
// prints: this is a tést
</code></pre>
<h3>Class Method: Buffer.alloc(size[, fill[, encoding]])<span><a class="mark" href="#buffer_class_method_buffer_alloc_size_fill_encoding" id="buffer_class_method_buffer_alloc_size_fill_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v4.5.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></li>
<li><code>fill</code> <span class="type"><Value></span> Default: <code>undefined</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> Default: <code>utf8</code></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 <em>zero-filled</em>.</p>
<pre><code class="lang-js">const buf = Buffer.alloc(5);
console.log(buf);
// <Buffer 00 00 00 00 00>
</code></pre>
<p>The <code>size</code> must be less than or equal to the value of
<code>require('buffer').kMaxLength</code> (on 64-bit architectures, <code>kMaxLength</code> is
<code>(2^31)-1</code>). Otherwise, a <a href="errors.html#errors_class_rangeerror"><code>RangeError</code></a> is thrown. If a <code>size</code> less than 0
is specified, a zero-length <code>Buffer</code> will be created.</p>
<p>If <code>fill</code> is specified, the allocated <code>Buffer</code> will be initialized by calling
<code>buf.fill(fill)</code>. See [<code>buf.fill()</code>][] for more information.</p>
<pre><code class="lang-js">const buf = Buffer.alloc(5, 'a');
console.log(buf);
// <Buffer 61 61 61 61 61>
</code></pre>
<p>If both <code>fill</code> and <code>encoding</code> are specified, the allocated <code>Buffer</code> will be
initialized by calling <code>buf.fill(fill, encoding)</code>. For example:</p>
<pre><code class="lang-js">const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
console.log(buf);
// <Buffer 68 65 6c 6c 6f 20 77 6f 72 6c 64>
</code></pre>
<p>Calling <code>Buffer.alloc(size)</code> can be significantly slower than the alternative
<code>Buffer.allocUnsafe(size)</code> but ensures that the newly created <code>Buffer</code> instance
contents will <em>never contain sensitive data</em>.</p>
<p>A <code>TypeError</code> will be thrown if <code>size</code> is not a number.</p>
<h3>Class Method: Buffer.allocUnsafe(size)<span><a class="mark" href="#buffer_class_method_buffer_allocunsafe_size" id="buffer_class_method_buffer_allocunsafe_size">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v4.5.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></li>
</ul>
<p>Allocates a new <em>non-zero-filled</em> <code>Buffer</code> of <code>size</code> bytes. The <code>size</code> must
be less than or equal to the value of <code>require('buffer').kMaxLength</code> (on 64-bit
architectures, <code>kMaxLength</code> is <code>(2^31)-1</code>). Otherwise, a <a href="errors.html#errors_class_rangeerror"><code>RangeError</code></a> is
thrown. If a <code>size</code> less than 0 is specified, a zero-length <code>Buffer</code> will be
created.</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="#buffer_buf_fill_value_offset_end"><code>buf.fill(0)</code></a> to initialize such
<code>Buffer</code> instances to zeroes.</p>
<pre><code class="lang-js">const buf = Buffer.allocUnsafe(5);
console.log(buf);
// <Buffer 78 e0 82 02 01>
// (octets will be different, every time)
buf.fill(0);
console.log(buf);
// <Buffer 00 00 00 00 00>
</code></pre>
<p>A <code>TypeError</code> will be thrown if <code>size</code> is not a number.</p>
<p>Note that the <code>Buffer</code> module pre-allocates an internal <code>Buffer</code> instance of
size <code>Buffer.poolSize</code> that is used as a pool for the fast allocation of new
<code>Buffer</code> instances created using <code>Buffer.allocUnsafe(size)</code> (and the
<code>new Buffer(size)</code> constructor) only when <code>size</code> is less than or equal to
<code>Buffer.poolSize >> 1</code> (floor of <code>Buffer.poolSize</code> divided by two). The default
value of <code>Buffer.poolSize</code> is <code>8192</code> but can be modified.</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 Buffer
pool, while <code>Buffer.allocUnsafe(size).fill(fill)</code> <em>will</em> use the internal
Buffer pool if <code>size</code> is less than or equal to half <code>Buffer.poolSize</code>. The
difference is subtle but can be important when an application requires the
additional performance that <code>Buffer.allocUnsafe(size)</code> provides.</p>
<h3>Class Method: Buffer.allocUnsafeSlow(size)<span><a class="mark" href="#buffer_class_method_buffer_allocunsafeslow_size" id="buffer_class_method_buffer_allocunsafeslow_size">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v4.5.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></li>
</ul>
<p>Allocates a new <em>non-zero-filled</em> and non-pooled <code>Buffer</code> of <code>size</code> bytes. The
<code>size</code> must be less than or equal to the value of
<code>require('buffer').kMaxLength</code> (on 64-bit architectures, <code>kMaxLength</code> is
<code>(2^31)-1</code>). Otherwise, a <a href="errors.html#errors_class_rangeerror"><code>RangeError</code></a> is thrown. If a <code>size</code> less than 0
is specified, a zero-length <code>Buffer</code> will be created.</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="#buffer_buf_fill_value_offset_end"><code>buf.fill(0)</code></a> to initialize such
<code>Buffer</code> instances to zeroes.</p>
<p>When using <code>Buffer.allocUnsafe()</code> to allocate new <code>Buffer</code> instances,
allocations under 4KB are, by default, sliced from a single pre-allocated
<code>Buffer</code>. This allows applications to avoid the garbage collection overhead of
creating many individually allocated Buffers. This approach improves both
performance and memory usage by eliminating the need to track and cleanup as
many <code>Persistent</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 Buffer instance using <code>Buffer.allocUnsafeSlow()</code> then
copy out the relevant bits.</p>
<pre><code class="lang-js">// need to keep around a few small chunks of memory
const store = [];
socket.on('readable', () => {
const data = socket.read();
// allocate for retained data
const sb = Buffer.allocUnsafeSlow(10);
// copy the data into the new allocation
data.copy(sb, 0, 0, 10);
store.push(sb);
});
</code></pre>
<p>Use of <code>Buffer.allocUnsafeSlow()</code> should be used only as a last resort <em>after</em>
a developer has observed undue memory retention in their applications.</p>
<p>A <code>TypeError</code> will be thrown if <code>size</code> is not a number.</p>
<h3>Class Method: Buffer.byteLength(string[, encoding])<span><a class="mark" href="#buffer_class_method_buffer_bytelength_string_encoding" id="buffer_class_method_buffer_bytelength_string_encoding">#</a></span></h3>
<div class="signature"><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>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> Default: <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></li>
</ul>
</div><p>Returns the actual byte length of a string. 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> since that returns the number of <em>characters</em> in
a string.</p>
<p><em>Note</em> that for <code>'base64'</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>
<p>Example:</p>
<pre><code class="lang-js">const str = '\u00bd + \u00bc = \u00be';
console.log(`${str}: ${str.length} characters, ` +
`${Buffer.byteLength(str, 'utf8')} bytes`);
// ½ + ¼ = ¾: 9 characters, 12 bytes
</code></pre>
<h3>Class Method: Buffer.compare(buf1, buf2)<span><a class="mark" href="#buffer_class_method_buffer_compare_buf1_buf2" id="buffer_class_method_buffer_compare_buf1_buf2">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.13</span>
</div><ul>
<li><code>buf1</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li>
<li><code>buf2</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></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>Compares <code>buf1</code> to <code>buf2</code> typically for the purpose of sorting arrays of
Buffers. This is equivalent is calling <a href="#buffer_buf_compare_otherbuffer"><code>buf1.compare(buf2)</code></a>.</p>
<pre><code class="lang-js">const arr = [Buffer('1234'), Buffer('0123')];
arr.sort(Buffer.compare);
</code></pre>
<h3>Class Method: Buffer.concat(list[, totalLength])<span><a class="mark" href="#buffer_class_method_buffer_concat_list_totallength" id="buffer_class_method_buffer_concat_list_totallength">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.11</span>
</div><ul>
<li><code>list</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> List of Buffer objects to concat</li>
<li><code>totalLength</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Total length of the Buffers in the list when concatenated</li>
<li>Returns: <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li>
</ul>
<p>Returns a new Buffer which is the result of concatenating all the Buffers 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
Buffer is returned.</p>
<p>If <code>totalLength</code> is not provided, it is calculated from the Buffers in the
<code>list</code>. This, however, adds an additional loop to the function, so it is faster
to provide the length explicitly.</p>
<p>Example: build a single Buffer from a list of three Buffers:</p>
<pre><code class="lang-js">const buf1 = new Buffer(10).fill(0);
const buf2 = new Buffer(14).fill(0);
const buf3 = new Buffer(18).fill(0);
const totalLength = buf1.length + buf2.length + buf3.length;
console.log(totalLength);
const bufA = Buffer.concat([buf1, buf2, buf3], totalLength);
console.log(bufA);
console.log(bufA.length);
// 42
// <Buffer 00 00 00 00 ...>
// 42
</code></pre>
<h3>Class Method: Buffer.from(array)<span><a class="mark" href="#buffer_class_method_buffer_from_array" id="buffer_class_method_buffer_from_array">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v4.5.0</span>
</div><ul>
<li><code>array</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
<p>Allocates a new <code>Buffer</code> using an <code>array</code> of octets.</p>
<pre><code class="lang-js">const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]);
// creates a new Buffer containing ASCII bytes
// ['b','u','f','f','e','r']
</code></pre>
<p>A <code>TypeError</code> will be thrown if <code>array</code> is not an <code>Array</code>.</p>
<h3>Class Method: Buffer.from(arrayBuffer)<span><a class="mark" href="#buffer_class_method_buffer_from_arraybuffer" id="buffer_class_method_buffer_from_arraybuffer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v4.5.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> The <code>.buffer</code> property of a <code>TypedArray</code> or
a <code>new ArrayBuffer()</code></li>
</ul>
<p>When passed a reference to the <code>.buffer</code> property of a <code>TypedArray</code> instance,
the newly created <code>Buffer</code> will share the same allocated memory as the
TypedArray.</p>
<pre><code class="lang-js">const arr = new Uint16Array(2);
arr[0] = 5000;
arr[1] = 4000;
const buf = Buffer.from(arr.buffer); // shares the memory with arr;
console.log(buf);
// Prints: <Buffer 88 13 a0 0f>
// changing the TypedArray changes the Buffer also
arr[1] = 6000;
console.log(buf);
// Prints: <Buffer 88 13 70 17>
</code></pre>
<p>A <code>TypeError</code> will be thrown if <code>arrayBuffer</code> is not an <code>ArrayBuffer</code>.</p>
<h3>Class Method: Buffer.from(buffer)<span><a class="mark" href="#buffer_class_method_buffer_from_buffer" id="buffer_class_method_buffer_from_buffer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v4.5.0</span>
</div><ul>
<li><code>buffer</code> <a href="buffer.html#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><code class="lang-js">const buf1 = Buffer.from('buffer');
const buf2 = Buffer.from(buf1);
buf1[0] = 0x61;
console.log(buf1.toString());
// 'auffer'
console.log(buf2.toString());
// 'buffer' (copy is not changed)
</code></pre>
<p>A <code>TypeError</code> will be thrown if <code>buffer</code> is not a <code>Buffer</code>.</p>
<h3>Class Method: Buffer.from(str[, encoding])<span><a class="mark" href="#buffer_class_method_buffer_from_str_encoding" id="buffer_class_method_buffer_from_str_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v4.5.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> 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> Encoding to use, Default: <code>'utf8'</code></li>
</ul>
<p>Creates a new <code>Buffer</code> containing the given JavaScript string <code>str</code>. If
provided, the <code>encoding</code> parameter identifies the character encoding.
If not provided, <code>encoding</code> defaults to <code>'utf8'</code>.</p>
<pre><code class="lang-js">const buf1 = Buffer.from('this is a tést');
console.log(buf1.toString());
// prints: this is a tést
console.log(buf1.toString('ascii'));
// prints: this is a tC)st
const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex');
console.log(buf2.toString());
// prints: this is a tést
</code></pre>
<p>A <code>TypeError</code> will be thrown if <code>str</code> is not a string.</p>
<h3>Class Method: Buffer.isBuffer(obj)<span><a class="mark" href="#buffer_class_method_buffer_isbuffer_obj" id="buffer_class_method_buffer_isbuffer_obj">#</a></span></h3>
<div class="signature"><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>
</div><p>Returns 'true' if <code>obj</code> is a Buffer.</p>
<h3>Class Method: Buffer.isEncoding(encoding)<span><a class="mark" href="#buffer_class_method_buffer_isencoding_encoding" id="buffer_class_method_buffer_isencoding_encoding">#</a></span></h3>
<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> The encoding string to test</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 true if the <code>encoding</code> is a valid encoding argument, or false
otherwise.</p>
<h3>buf[index]<span><a class="mark" href="#buffer_buf_index" id="buffer_buf_index">#</a></span></h3>
<div class="api_metadata">
</div><p>The index operator <code>[index]</code> can be used to get and set the octet at position
<code>index</code> in the Buffer. 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>Example: copy an ASCII string into a Buffer, one byte at a time:</p>
<pre><code class="lang-js">const str = "Node.js";
const buf = new Buffer(str.length);
for (var i = 0; i < str.length ; i++) {
buf[i] = str.charCodeAt(i);
}
console.log(buf.toString('ascii'));
// Prints: Node.js
</code></pre>
<h3>buf.compare(otherBuffer)<span><a class="mark" href="#buffer_buf_compare_otherbuffer" id="buffer_buf_compare_otherbuffer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.13</span>
</div><ul>
<li><code>otherBuffer</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></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>Compares two Buffer instances and returns a number indicating whether <code>buf</code>
comes before, after, or is the same as the <code>otherBuffer</code> in sort order.
Comparison is based on the actual sequence of bytes in each Buffer.</p>
<ul>
<li><code>0</code> is returned if <code>otherBuffer</code> is the same as <code>buf</code></li>
<li><code>1</code> is returned if <code>otherBuffer</code> should come <em>before</em> <code>buf</code> when sorted.</li>
<li><code>-1</code> is returned if <code>otherBuffer</code> should come <em>after</em> <code>buf</code> when sorted.</li>
</ul>
<pre><code class="lang-js">const buf1 = new Buffer('ABC');
const buf2 = new Buffer('BCD');
const buf3 = new Buffer('ABCD');
console.log(buf1.compare(buf1));
// Prints: 0
console.log(buf1.compare(buf2));
// Prints: -1
console.log(buf1.compare(buf3));
// Prints: -1
console.log(buf2.compare(buf1));
// Prints: 1
console.log(buf2.compare(buf3));
// Prints: 1
[buf1, buf2, buf3].sort(Buffer.compare);
// produces sort order [buf1, buf3, buf2]
</code></pre>
<h3>buf.copy(targetBuffer[, targetStart[, sourceStart[, sourceEnd]]])<span><a class="mark" href="#buffer_buf_copy_targetbuffer_targetstart_sourcestart_sourceend" id="buffer_buf_copy_targetbuffer_targetstart_sourcestart_sourceend">#</a></span></h3>
<div class="signature"><ul>
<li><code>targetBuffer</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> Buffer 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"><Number></a> Default: 0</li>
<li><code>sourceStart</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Default: 0</li>
<li><code>sourceEnd</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Default: <code>buffer.length</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 copied.</li>
</ul>
</div><p>Copies data from a region of this Buffer to a region in the target Buffer even
if the target memory region overlaps with the source.</p>
<p>Example: build two Buffers, then copy <code>buf1</code> from byte 16 through byte 19
into <code>buf2</code>, starting at the 8th byte in <code>buf2</code>.</p>
<pre><code class="lang-js">const buf1 = new Buffer(26);
const buf2 = new Buffer(26).fill('!');
for (var i = 0 ; i < 26 ; i++) {
buf1[i] = i + 97; // 97 is ASCII a
}
buf1.copy(buf2, 8, 16, 20);
console.log(buf2.toString('ascii', 0, 25));
// Prints: !!!!!!!!qrst!!!!!!!!!!!!!
</code></pre>
<p>Example: Build a single Buffer, then copy data from one region to an overlapping
region in the same Buffer</p>
<pre><code class="lang-js">const buf = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
buf[i] = i + 97; // 97 is ASCII a
}
buf.copy(buf, 0, 4, 10);
console.log(buf.toString());
// efghijghijklmnopqrstuvwxyz
</code></pre>
<h3>buf.entries()<span><a class="mark" href="#buffer_buf_entries" id="buffer_buf_entries">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.1.0</span>
</div><ul>
<li>Returns: <span class="type"><Iterator></span></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 Buffer
contents.</p>
<pre><code class="lang-js">const buf = new Buffer('buffer');
for (var pair of buf.entries()) {
console.log(pair);
}
// prints:
// [0, 98]
// [1, 117]
// [2, 102]
// [3, 102]
// [4, 101]
// [5, 114]
</code></pre>
<h3>buf.equals(otherBuffer)<span><a class="mark" href="#buffer_buf_equals_otherbuffer" id="buffer_buf_equals_otherbuffer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.0.0</span>
</div><ul>
<li><code>otherBuffer</code> <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></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 a boolean indicating whether <code>this</code> and <code>otherBuffer</code> have exactly the
same bytes.</p>
<pre><code class="lang-js">const buf1 = new Buffer('ABC');
const buf2 = new Buffer('414243', 'hex');
const buf3 = new Buffer('ABCD');
console.log(buf1.equals(buf2));
// Prints: true
console.log(buf1.equals(buf3));
// Prints: false
</code></pre>
<h3>buf.fill(value[, offset[, end]])<span><a class="mark" href="#buffer_buf_fill_value_offset_end" id="buffer_buf_fill_value_offset_end">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.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="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a></li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Default: 0</li>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Default: <code>buffer.length</code></li>
<li>Returns: <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li>
</ul>
<p>Fills the Buffer with the specified value. If the <code>offset</code> and <code>end</code> are not
given it will fill the entire Buffer. The method returns a reference to the
Buffer so calls can be chained.</p>
<pre><code class="lang-js">const b = new Buffer(50).fill('h');
console.log(b.toString());
// Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh
</code></pre>
<h3>buf.indexOf(value[, byteOffset][, encoding])<span><a class="mark" href="#buffer_buf_indexof_value_byteoffset_encoding" id="buffer_buf_indexof_value_byteoffset_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.5.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="buffer.html#buffer_class_buffer" class="type"><Buffer></a> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a></li>
<li><code>byteOffset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Default: 0</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> Default: <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></li>
</ul>
<p>Operates similar to <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf"><code>Array#indexOf()</code></a> in that it returns either the
starting index position of <code>value</code> in Buffer or <code>-1</code> if the Buffer does not
contain <code>value</code>. The <code>value</code> can be a String, Buffer or Number. Strings are by
default interpreted as UTF8. Buffers will use the entire Buffer (to compare a
partial Buffer use <a href="#buffer_buf_slice_start_end"><code>buf.slice()</code></a>). Numbers will be interpreted as unsigned 8-bit
integer values between <code>0</code> and <code>255</code>.</p>
<pre><code class="lang-js">const buf = new Buffer('this is a buffer');
buf.indexOf('this');
// returns 0
buf.indexOf('is');
// returns 2
buf.indexOf(new Buffer('a buffer'));
// returns 8
buf.indexOf(97); // ascii for 'a'
// returns 8
buf.indexOf(new Buffer('a buffer example'));
// returns -1
buf.indexOf(new Buffer('a buffer example').slice(0,8));
// returns 8
const utf16Buffer = new Buffer('\u039a\u0391\u03a3\u03a3\u0395', 'ucs2');
utf16Buffer.indexOf('\u03a3', 0, 'ucs2');
// returns 4
utf16Buffer.indexOf('\u03a3', -4, 'ucs2');
// returns 6
</code></pre>
<h3>buf.keys()<span><a class="mark" href="#buffer_buf_keys" id="buffer_buf_keys">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.1.0</span>
</div><ul>
<li>Returns: <span class="type"><Iterator></span></li>
</ul>
<p>Creates and returns an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">iterator</a> of Buffer keys (indices).</p>
<pre><code class="lang-js">const buf = new Buffer('buffer');
for (var key of buf.keys()) {
console.log(key);
}
// prints:
// 0
// 1
// 2
// 3
// 4
// 5
</code></pre>
<h3>buf.length<span><a class="mark" href="#buffer_buf_length" id="buffer_buf_length">#</a></span></h3>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a></li>
</ul>
</div><p>Returns the amount of memory allocated for the Buffer in number of bytes. Note
that this does not necessarily reflect the amount of usable data within the
Buffer. For instance, in the example below, a Buffer with 1234 bytes is
allocated, but only 11 ASCII bytes are written.</p>
<pre><code class="lang-js">const buf = new Buffer(1234);
console.log(buf.length);
// Prints: 1234
buf.write('some string', 0, 'ascii');
console.log(buf.length);
// Prints: 1234
</code></pre>
<p>While the <code>length</code> property is not immutable, changing the value of <code>length</code>
can result in undefined and inconsistent behavior. Applications that wish to
modify the length of a Buffer should therefore treat <code>length</code> as read-only and
use <a href="#buffer_buf_slice_start_end"><code>buf.slice()</code></a> to create a new Buffer.</p>
<pre><code class="lang-js">var buf = new Buffer(10);
buf.write('abcdefghj', 0, 'ascii');
console.log(buf.length);
// Prints: 10
buf = buf.slice(0,5);
console.log(buf.length);
// Prints: 5
</code></pre>
<h3>buf.readDoubleBE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readdoublebe_offset_noassert" id="buffer_buf_readdoublebe_offset_noassert">#</a></span></h3>
<h3>buf.readDoubleLE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readdoublele_offset_noassert" id="buffer_buf_readdoublele_offset_noassert">#</a></span></h3>
<div class="signature"><ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> <code>0 <= offset <= buf.length - 8</code></li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Default: false</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a></li>
</ul>
</div><p>Reads a 64-bit double from the Buffer at the specified <code>offset</code> with specified
endian format (<code>readDoubleBE()</code> returns big endian, <code>readDoubleLE()</code> returns
little endian).</p>
<p>Setting <code>noAssert</code> to <code>true</code> skips validation of the <code>offset</code>. This allows the
<code>offset</code> to be beyond the end of the Buffer.</p>
<pre><code class="lang-js">const buf = new Buffer([1,2,3,4,5,6,7,8]);
buf.readDoubleBE();
// Returns: 8.20788039913184e-304
buf.readDoubleLE();
// Returns: 5.447603722011605e-270
buf.readDoubleLE(1);
// throws RangeError: Index out of range
buf.readDoubleLE(1, true); // Warning: reads passed end of buffer!
// Segmentation fault! don't do this!
</code></pre>
<h3>buf.readFloatBE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readfloatbe_offset_noassert" id="buffer_buf_readfloatbe_offset_noassert">#</a></span></h3>
<h3>buf.readFloatLE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readfloatle_offset_noassert" id="buffer_buf_readfloatle_offset_noassert">#</a></span></h3>
<div class="signature"><ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> <code>0 <= offset <= buf.length - 4</code></li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Default: false</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a></li>
</ul>
</div><p>Reads a 32-bit float from the Buffer at the specified <code>offset</code> with specified
endian format (<code>readFloatBE()</code> returns big endian, <code>readFloatLE()</code> returns
little endian).</p>
<p>Setting <code>noAssert</code> to <code>true</code> skips validation of the <code>offset</code>. This allows the
<code>offset</code> to be beyond the end of the Buffer.</p>
<pre><code class="lang-js">const buf = new Buffer([1,2,3,4]);
buf.readFloatBE();
// Returns: 2.387939260590663e-38
buf.readFloatLE();
// Returns: 1.539989614439558e-36
buf.readFloatLE(1);
// throws RangeError: Index out of range
buf.readFloatLE(1, true); // Warning: reads passed end of buffer!
// Segmentation fault! don't do this!
</code></pre>
<h3>buf.readInt8(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readint8_offset_noassert" id="buffer_buf_readint8_offset_noassert">#</a></span></h3>
<div class="signature"><ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> <code>0 <= offset <= buf.length - 1</code></li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Default: false</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a></li>
</ul>
</div><p>Reads a signed 8-bit integer from the Buffer at the specified <code>offset</code>.</p>
<p>Setting <code>noAssert</code> to <code>true</code> skips validation of the <code>offset</code>. This allows the
<code>offset</code> to be beyond the end of the Buffer.</p>
<p>Integers read from the Buffer are interpreted as two's complement signed values.</p>
<pre><code class="lang-js">const buf = new Buffer([1,-2,3,4]);
buf.readInt8(0);
// returns 1
buf.readInt8(1);
// returns -2
</code></pre>
<h3>buf.readInt16BE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readint16be_offset_noassert" id="buffer_buf_readint16be_offset_noassert">#</a></span></h3>
<h3>buf.readInt16LE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readint16le_offset_noassert" id="buffer_buf_readint16le_offset_noassert">#</a></span></h3>
<div class="signature"><ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> <code>0 <= offset <= buf.length - 2</code></li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Default: false</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a></li>
</ul>
</div><p>Reads a signed 16-bit integer from the Buffer at the specified <code>offset</code> with
the specified endian format (<code>readInt16BE()</code> returns big endian,
<code>readInt16LE()</code> returns little endian).</p>
<p>Setting <code>noAssert</code> to <code>true</code> skips validation of the <code>offset</code>. This allows the
<code>offset</code> to be beyond the end of the Buffer.</p>
<p>Integers read from the Buffer are interpreted as two's complement signed values.</p>
<pre><code class="lang-js">const buf = new Buffer([1,-2,3,4]);
buf.readInt16BE();
// returns 510
buf.readInt16LE(1);
// returns 1022
</code></pre>
<h3>buf.readInt32BE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readint32be_offset_noassert" id="buffer_buf_readint32be_offset_noassert">#</a></span></h3>
<h3>buf.readInt32LE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readint32le_offset_noassert" id="buffer_buf_readint32le_offset_noassert">#</a></span></h3>
<div class="signature"><ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> <code>0 <= offset <= buf.length - 4</code></li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Default: false</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a></li>
</ul>
</div><p>Reads a signed 32-bit integer from the Buffer at the specified <code>offset</code> with
the specified endian format (<code>readInt32BE()</code> returns big endian,
<code>readInt32LE()</code> returns little endian).</p>
<p>Setting <code>noAssert</code> to <code>true</code> skips validation of the <code>offset</code>. This allows the
<code>offset</code> to be beyond the end of the Buffer.</p>
<p>Integers read from the Buffer are interpreted as two's complement signed values.</p>
<pre><code class="lang-js">const buf = new Buffer([1,-2,3,4]);
buf.readInt32BE();
// returns 33424132
buf.readInt32LE();
// returns 67370497
buf.readInt32LE(1);
// throws RangeError: Index out of range
</code></pre>
<h3>buf.readIntBE(offset, byteLength[, noAssert])<span><a class="mark" href="#buffer_buf_readintbe_offset_bytelength_noassert" id="buffer_buf_readintbe_offset_bytelength_noassert">#</a></span></h3>
<h3>buf.readIntLE(offset, byteLength[, noAssert])<span><a class="mark" href="#buffer_buf_readintle_offset_bytelength_noassert" id="buffer_buf_readintle_offset_bytelength_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.0.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"><Number></a> <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"><Number></a> <code>0 < byteLength <= 6</code></li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Default: false</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 <code>byteLength</code> number of bytes from the Buffer at the specified <code>offset</code>
and interprets the result as a two's complement signed value. Supports up to 48
bits of accuracy. For example:</p>
<pre><code class="lang-js">const buf = new Buffer(6);
buf.writeUInt16LE(0x90ab, 0);
buf.writeUInt32LE(0x12345678, 2);
buf.readIntLE(0, 6).toString(16); // Specify 6 bytes (48 bits)
// Returns: '1234567890ab'
buf.readIntBE(0, 6).toString(16);
// Returns: -546f87a9cbee
</code></pre>
<p>Setting <code>noAssert</code> to <code>true</code> skips validation of the <code>offset</code>. This allows the
<code>offset</code> to be beyond the end of the Buffer.</p>
<h3>buf.readUInt8(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readuint8_offset_noassert" id="buffer_buf_readuint8_offset_noassert">#</a></span></h3>
<div class="signature"><ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> <code>0 <= offset <= buf.length - 1</code></li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Default: false</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a></li>
</ul>
</div><p>Reads an unsigned 8-bit integer from the Buffer at the specified <code>offset</code>.</p>
<p>Setting <code>noAssert</code> to <code>true</code> skips validation of the <code>offset</code>. This allows the
<code>offset</code> to be beyond the end of the Buffer.</p>
<pre><code class="lang-js">const buf = new Buffer([1,-2,3,4]);
buf.readUInt8(0);
// returns 1
buf.readUInt8(1);
// returns 254
</code></pre>
<h3>buf.readUInt16BE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readuint16be_offset_noassert" id="buffer_buf_readuint16be_offset_noassert">#</a></span></h3>
<h3>buf.readUInt16LE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readuint16le_offset_noassert" id="buffer_buf_readuint16le_offset_noassert">#</a></span></h3>
<div class="signature"><ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> <code>0 <= offset <= buf.length - 2</code></li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Default: false</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a></li>
</ul>
</div><p>Reads an unsigned 16-bit integer from the Buffer at the specified <code>offset</code> with
specified endian format (<code>readUInt16BE()</code> returns big endian,
<code>readUInt16LE()</code> returns little endian).</p>
<p>Setting <code>noAssert</code> to <code>true</code> skips validation of the <code>offset</code>. This allows the
<code>offset</code> to be beyond the end of the Buffer.</p>
<p>Example:</p>
<pre><code class="lang-js">const buf = new Buffer([0x3, 0x4, 0x23, 0x42]);
buf.readUInt16BE(0);
// Returns: 0x0304
buf.readUInt16LE(0);
// Returns: 0x0403
buf.readUInt16BE(1);
// Returns: 0x0423
buf.readUInt16LE(1);
// Returns: 0x2304
buf.readUInt16BE(2);
// Returns: 0x2342
buf.readUInt16LE(2);
// Returns: 0x4223
</code></pre>
<h3>buf.readUInt32BE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readuint32be_offset_noassert" id="buffer_buf_readuint32be_offset_noassert">#</a></span></h3>
<h3>buf.readUInt32LE(offset[, noAssert])<span><a class="mark" href="#buffer_buf_readuint32le_offset_noassert" id="buffer_buf_readuint32le_offset_noassert">#</a></span></h3>
<div class="signature"><ul>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> <code>0 <= offset <= buf.length - 4</code></li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Default: false</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a></li>
</ul>
</div><p>Reads an unsigned 32-bit integer from the Buffer at the specified <code>offset</code> with
specified endian format (<code>readUInt32BE()</code> returns big endian,
<code>readUInt32LE()</code> returns little endian).</p>
<p>Setting <code>noAssert</code> to <code>true</code> skips validation of the <code>offset</code>. This allows the
<code>offset</code> to be beyond the end of the Buffer.</p>
<p>Example:</p>
<pre><code class="lang-js">const buf = new Buffer([0x3, 0x4, 0x23, 0x42]);
buf.readUInt32BE(0);
// Returns: 0x03042342
console.log(buf.readUInt32LE(0));
// Returns: 0x42230403
</code></pre>
<h3>buf.readUIntBE(offset, byteLength[, noAssert])<span><a class="mark" href="#buffer_buf_readuintbe_offset_bytelength_noassert" id="buffer_buf_readuintbe_offset_bytelength_noassert">#</a></span></h3>
<h3>buf.readUIntLE(offset, byteLength[, noAssert])<span><a class="mark" href="#buffer_buf_readuintle_offset_bytelength_noassert" id="buffer_buf_readuintle_offset_bytelength_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.0.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"><Number></a> <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"><Number></a> <code>0 < byteLength <= 6</code></li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Default: false</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 <code>byteLength</code> number of bytes from the Buffer at the specified <code>offset</code>
and interprets the result as an unsigned integer. Supports up to 48
bits of accuracy. For example:</p>
<pre><code class="lang-js">const buf = new Buffer(6);
buf.writeUInt16LE(0x90ab, 0);
buf.writeUInt32LE(0x12345678, 2);
buf.readUIntLE(0, 6).toString(16); // Specify 6 bytes (48 bits)
// Returns: '1234567890ab'
buf.readUIntBE(0, 6).toString(16);
// Returns: ab9078563412
</code></pre>
<p>Setting <code>noAssert</code> to <code>true</code> skips validation of the <code>offset</code>. This allows the
<code>offset</code> to be beyond the end of the Buffer.</p>
<h3>buf.slice([start[, end]])<span><a class="mark" href="#buffer_buf_slice_start_end" id="buffer_buf_slice_start_end">#</a></span></h3>
<div class="signature"><ul>
<li><code>start</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Default: 0</li>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Default: <code>buffer.length</code></li>
<li>Returns: <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li>
</ul>
</div><p>Returns a new Buffer that references the same memory as the original, but
offset and cropped by the <code>start</code> and <code>end</code> indices.</p>
<p><strong>Note that modifying the new Buffer slice will modify the memory in the
original Buffer because the allocated memory of the two objects overlap.</strong></p>
<p>Example: build a Buffer with the ASCII alphabet, take a slice, then modify one
byte from the original Buffer.</p>
<pre><code class="lang-js">const buf1 = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
buf1[i] = i + 97; // 97 is ASCII a
}
const buf2 = buf1.slice(0, 3);
buf2.toString('ascii', 0, buf2.length);
// Returns: 'abc'
buf1[0] = 33;
buf2.toString('ascii', 0, buf2.length);
// Returns : '!bc'
</code></pre>
<p>Specifying negative indexes causes the slice to be generated relative to the
end of the Buffer rather than the beginning.</p>
<pre><code class="lang-js">const buf = new Buffer('buffer');
buf.slice(-6, -1).toString();
// Returns 'buffe', equivalent to buf.slice(0, 5)
buf.slice(-6, -2).toString();
// Returns 'buff', equivalent to buf.slice(0, 4)
buf.slice(-5, -2).toString();
// Returns 'uff', equivalent to buf.slice(1, 4)
</code></pre>
<h3>buf.toString([encoding[, start[, end]]])<span><a class="mark" href="#buffer_buf_tostring_encoding_start_end" id="buffer_buf_tostring_encoding_start_end">#</a></span></h3>
<div class="signature"><ul>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> Default: <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"><Number></a> Default: 0</li>
<li><code>end</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Default: <code>buffer.length</code></li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a></li>
</ul>
</div><p>Decodes and returns a string from the Buffer data using the specified
character set <code>encoding</code>.</p>
<pre><code class="lang-js">const buf = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
buf[i] = i + 97; // 97 is ASCII a
}
buf.toString('ascii');
// Returns: 'abcdefghijklmnopqrstuvwxyz'
buf.toString('ascii',0,5);
// Returns: 'abcde'
buf.toString('utf8',0,5);
// Returns: 'abcde'
buf.toString(undefined,0,5);
// Returns: 'abcde', encoding defaults to 'utf8'
</code></pre>
<h3>buf.toJSON()<span><a class="mark" href="#buffer_buf_tojson" id="buffer_buf_tojson">#</a></span></h3>
<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 the Buffer instance. <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 Buffer instance.</p>
<p>Example:</p>
<pre><code class="lang-js">const buf = new Buffer('test');
const json = JSON.stringify(buf);
console.log(json);
// Prints: '{"type":"Buffer","data":[116,101,115,116]}'
const copy = JSON.parse(json, (key, value) => {
return value && value.type === 'Buffer'
? new Buffer(value.data)
: value;
});
console.log(copy.toString());
// Prints: 'test'
</code></pre>
<h3>buf.values()<span><a class="mark" href="#buffer_buf_values" id="buffer_buf_values">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.1.0</span>
</div><ul>
<li>Returns: <span class="type"><Iterator></span></li>
</ul>
<p>Creates and returns an <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols">iterator</a> for Buffer values (bytes). This function is
called automatically when the Buffer is used in a <code>for..of</code> statement.</p>
<pre><code class="lang-js">const buf = new Buffer('buffer');
for (var value of buf.values()) {
console.log(value);
}
// prints:
// 98
// 117
// 102
// 102
// 101
// 114
for (var value of buf) {
console.log(value);
}
// prints:
// 98
// 117
// 102
// 102
// 101
// 114
</code></pre>
<h3>buf.write(string[, offset[, length]][, encoding])<span><a class="mark" href="#buffer_buf_write_string_offset_length_encoding" id="buffer_buf_write_string_offset_length_encoding">#</a></span></h3>
<div class="signature"><ul>
<li><code>string</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> Bytes to be written to buffer</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Default: 0</li>
<li><code>length</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Default: <code>buffer.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> Default: <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> Numbers of bytes written</li>
</ul>
</div><p>Writes <code>string</code> to the Buffer at <code>offset</code> using the given <code>encoding</code>.
The <code>length</code> parameter is the number of bytes to write. If the Buffer did not
contain enough space to fit the entire string, only a partial amount of the
string will be written however, it will not write only partially encoded
characters.</p>
<pre><code class="lang-js">const buf = new Buffer(256);
const len = buf.write('\u00bd + \u00bc = \u00be', 0);
console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`);
// Prints: 12 bytes: ½ + ¼ = ¾
</code></pre>
<h3>buf.writeDoubleBE(value, offset[, noAssert])<span><a class="mark" href="#buffer_buf_writedoublebe_value_offset_noassert" id="buffer_buf_writedoublebe_value_offset_noassert">#</a></span></h3>
<h3>buf.writeDoubleLE(value, offset[, noAssert])<span><a class="mark" href="#buffer_buf_writedoublele_value_offset_noassert" id="buffer_buf_writedoublele_value_offset_noassert">#</a></span></h3>
<div class="signature"><ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Bytes to be written to Buffer</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> <code>0 <= offset <= buf.length - 8</code></li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Default: false</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> The offset plus the number of written bytes</li>
</ul>
</div><p>Writes <code>value</code> to the Buffer at the specified <code>offset</code> with specified endian
format (<code>writeDoubleBE()</code> writes big endian, <code>writeDoubleLE()</code> writes little
endian). The <code>value</code> argument <em>should</em> be a valid 64-bit double. Behavior is
not defined when <code>value</code> is anything other than a 64-bit double.</p>
<p>Set <code>noAssert</code> to true to skip validation of <code>value</code> and <code>offset</code>. This means
that <code>value</code> may be too large for the specific function and <code>offset</code> may be
beyond the end of the Buffer leading to the values being silently dropped. This
should not be used unless you are certain of correctness.</p>
<p>Example:</p>
<pre><code class="lang-js">const buf = new Buffer(8);
buf.writeDoubleBE(0xdeadbeefcafebabe, 0);
console.log(buf);
// Prints: <Buffer 43 eb d5 b7 dd f9 5f d7>
buf.writeDoubleLE(0xdeadbeefcafebabe, 0);
console.log(buf);
// Prints: <Buffer d7 5f f9 dd b7 d5 eb 43>
</code></pre>
<h3>buf.writeFloatBE(value, offset[, noAssert])<span><a class="mark" href="#buffer_buf_writefloatbe_value_offset_noassert" id="buffer_buf_writefloatbe_value_offset_noassert">#</a></span></h3>
<h3>buf.writeFloatLE(value, offset[, noAssert])<span><a class="mark" href="#buffer_buf_writefloatle_value_offset_noassert" id="buffer_buf_writefloatle_value_offset_noassert">#</a></span></h3>
<div class="signature"><ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Bytes to be written to Buffer</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> <code>0 <= offset <= buf.length - 4</code></li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Default: false</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> The offset plus the number of written bytes</li>
</ul>
</div><p>Writes <code>value</code> to the Buffer at the specified <code>offset</code> with specified endian
format (<code>writeFloatBE()</code> writes big endian, <code>writeFloatLE()</code> writes little
endian). Behavior is not defined when <code>value</code> is anything other than a 32-bit
float.</p>
<p>Set <code>noAssert</code> to true to skip validation of <code>value</code> and <code>offset</code>. This means
that <code>value</code> may be too large for the specific function and <code>offset</code> may be
beyond the end of the Buffer leading to the values being silently dropped. This
should not be used unless you are certain of correctness.</p>
<p>Example:</p>
<pre><code class="lang-js">const buf = new Buffer(4);
buf.writeFloatBE(0xcafebabe, 0);
console.log(buf);
// Prints: <Buffer 4f 4a fe bb>
buf.writeFloatLE(0xcafebabe, 0);
console.log(buf);
// Prints: <Buffer bb fe 4a 4f>
</code></pre>
<h3>buf.writeInt8(value, offset[, noAssert])<span><a class="mark" href="#buffer_buf_writeint8_value_offset_noassert" id="buffer_buf_writeint8_value_offset_noassert">#</a></span></h3>
<div class="signature"><ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Bytes to be written to Buffer</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> <code>0 <= offset <= buf.length - 1</code></li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Default: false</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> The offset plus the number of written bytes</li>
</ul>
</div><p>Writes <code>value</code> to the Buffer at the specified <code>offset</code>. The <code>value</code> should be a
valid signed 8-bit integer. Behavior is not defined when <code>value</code> is anything
other than a signed 8-bit integer.</p>
<p>Set <code>noAssert</code> to true to skip validation of <code>value</code> and <code>offset</code>. This means
that <code>value</code> may be too large for the specific function and <code>offset</code> may be
beyond the end of the Buffer leading to the values being silently dropped. This
should not be used unless you are certain of correctness.</p>
<p>The <code>value</code> is interpreted and written as a two's complement signed integer.</p>
<pre><code class="lang-js">const buf = new Buffer(2);
buf.writeInt8(2, 0);
buf.writeInt8(-2, 1);
console.log(buf);
// Prints: <Buffer 02 fe>
</code></pre>
<h3>buf.writeInt16BE(value, offset[, noAssert])<span><a class="mark" href="#buffer_buf_writeint16be_value_offset_noassert" id="buffer_buf_writeint16be_value_offset_noassert">#</a></span></h3>
<h3>buf.writeInt16LE(value, offset[, noAssert])<span><a class="mark" href="#buffer_buf_writeint16le_value_offset_noassert" id="buffer_buf_writeint16le_value_offset_noassert">#</a></span></h3>
<div class="signature"><ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Bytes to be written to Buffer</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> <code>0 <= offset <= buf.length - 2</code></li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Default: false</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> The offset plus the number of written bytes</li>
</ul>
</div><p>Writes <code>value</code> to the Buffer at the specified <code>offset</code> with specified endian
format (<code>writeInt16BE()</code> writes big endian, <code>writeInt16LE()</code> writes little
endian). The <code>value</code> should be a valid signed 16-bit integer. Behavior is
not defined when <code>value</code> is anything other than a signed 16-bit integer.</p>
<p>Set <code>noAssert</code> to true to skip validation of <code>value</code> and <code>offset</code>. This means
that <code>value</code> may be too large for the specific function and <code>offset</code> may be
beyond the end of the Buffer leading to the values being silently dropped. This
should not be used unless you are certain of correctness.</p>
<p>The <code>value</code> is interpreted and written as a two's complement signed integer.</p>
<pre><code class="lang-js">const buf = new Buffer(4);
buf.writeInt16BE(0x0102,0);
buf.writeInt16LE(0x0304,2);
console.log(buf);
// Prints: <Buffer 01 02 04 03>
</code></pre>
<h3>buf.writeInt32BE(value, offset[, noAssert])<span><a class="mark" href="#buffer_buf_writeint32be_value_offset_noassert" id="buffer_buf_writeint32be_value_offset_noassert">#</a></span></h3>
<h3>buf.writeInt32LE(value, offset[, noAssert])<span><a class="mark" href="#buffer_buf_writeint32le_value_offset_noassert" id="buffer_buf_writeint32le_value_offset_noassert">#</a></span></h3>
<div class="signature"><ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Bytes to be written to Buffer</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> <code>0 <= offset <= buf.length - 4</code></li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Default: false</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> The offset plus the number of written bytes</li>
</ul>
</div><p>Writes <code>value</code> to the Buffer at the specified <code>offset</code> with specified endian
format (<code>writeInt32BE()</code> writes big endian, <code>writeInt32LE()</code> writes little
endian). The <code>value</code> should be a valid signed 32-bit integer. Behavior is
not defined when <code>value</code> is anything other than a signed 32-bit integer.</p>
<p>Set <code>noAssert</code> to true to skip validation of <code>value</code> and <code>offset</code>. This means
that <code>value</code> may be too large for the specific function and <code>offset</code> may be
beyond the end of the Buffer leading to the values being silently dropped. This
should not be used unless you are certain of correctness.</p>
<p>The <code>value</code> is interpreted and written as a two's complement signed integer.</p>
<pre><code class="lang-js">const buf = new Buffer(8);
buf.writeInt32BE(0x01020304,0);
buf.writeInt32LE(0x05060708,4);
console.log(buf);
// Prints: <Buffer 01 02 03 04 08 07 06 05>
</code></pre>
<h3>buf.writeIntBE(value, offset, byteLength[, noAssert])<span><a class="mark" href="#buffer_buf_writeintbe_value_offset_bytelength_noassert" id="buffer_buf_writeintbe_value_offset_bytelength_noassert">#</a></span></h3>
<h3>buf.writeIntLE(value, offset, byteLength[, noAssert])<span><a class="mark" href="#buffer_buf_writeintle_value_offset_bytelength_noassert" id="buffer_buf_writeintle_value_offset_bytelength_noassert">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.0.0</span>
</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> Bytes to be written to Buffer</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> <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"><Number></a> <code>0 < byteLength <= 6</code></li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Default: false</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> The offset plus the number of written bytes</li>
</ul>
<p>Writes <code>value</code> to the Buffer at the specified <code>offset</code> and <code>byteLength</code>.
Supports up to 48 bits of accuracy. For example:</p>
<pre><code class="lang-js">const buf1 = new Buffer(6);
buf1.writeUIntBE(0x1234567890ab, 0, 6);
console.log(buf1);
// Prints: <Buffer 12 34 56 78 90 ab>
const buf2 = new Buffer(6);
buf2.writeUIntLE(0x1234567890ab, 0, 6);
console.log(buf2);
// Prints: <Buffer ab 90 78 56 34 12>
</code></pre>
<p>Set <code>noAssert</code> to true to skip validation of <code>value</code> and <code>offset</code>. This means
that <code>value</code> may be too large for the specific function and <code>offset</code> may be
beyond the end of the Buffer leading to the values being silently dropped. This
should not be used unless you are certain of correctness.</p>
<p>Behavior is not defined when <code>value</code> is anything other than an integer.</p>
<h3>buf.writeUInt8(value, offset[, noAssert])<span><a class="mark" href="#buffer_buf_writeuint8_value_offset_noassert" id="buffer_buf_writeuint8_value_offset_noassert">#</a></span></h3>
<div class="signature"><ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Bytes to be written to Buffer</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> <code>0 <= offset <= buf.length - 1</code></li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Default: false</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> The offset plus the number of written bytes</li>
</ul>
</div><p>Writes <code>value</code> to the Buffer at the specified <code>offset</code>. The <code>value</code> should be a
valid unsigned 8-bit integer. Behavior is not defined when <code>value</code> is anything
other than an unsigned 8-bit integer.</p>
<p>Set <code>noAssert</code> to true to skip validation of <code>value</code> and <code>offset</code>. This means
that <code>value</code> may be too large for the specific function and <code>offset</code> may be
beyond the end of the Buffer leading to the values being silently dropped. This
should not be used unless you are certain of correctness.</p>
<p>Example:</p>
<pre><code class="lang-js">const buf = new Buffer(4);
buf.writeUInt8(0x3, 0);
buf.writeUInt8(0x4, 1);
buf.writeUInt8(0x23, 2);
buf.writeUInt8(0x42, 3);
console.log(buf);
// Prints: <Buffer 03 04 23 42>
</code></pre>
<h3>buf.writeUInt16BE(value, offset[, noAssert])<span><a class="mark" href="#buffer_buf_writeuint16be_value_offset_noassert" id="buffer_buf_writeuint16be_value_offset_noassert">#</a></span></h3>
<h3>buf.writeUInt16LE(value, offset[, noAssert])<span><a class="mark" href="#buffer_buf_writeuint16le_value_offset_noassert" id="buffer_buf_writeuint16le_value_offset_noassert">#</a></span></h3>
<div class="signature"><ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Bytes to be written to Buffer</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> <code>0 <= offset <= buf.length - 2</code></li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Default: false</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> The offset plus the number of written bytes</li>
</ul>
</div><p>Writes <code>value</code> to the Buffer at the specified <code>offset</code> with specified endian
format (<code>writeUInt16BE()</code> writes big endian, <code>writeUInt16LE()</code> writes little
endian). The <code>value</code> should be a valid unsigned 16-bit integer. Behavior is
not defined when <code>value</code> is anything other than an unsigned 16-bit integer.</p>
<p>Set <code>noAssert</code> to true to skip validation of <code>value</code> and <code>offset</code>. This means
that <code>value</code> may be too large for the specific function and <code>offset</code> may be
beyond the end of the Buffer leading to the values being silently dropped. This
should not be used unless you are certain of correctness.</p>
<p>Example:</p>
<pre><code class="lang-js">const buf = new Buffer(4);
buf.writeUInt16BE(0xdead, 0);
buf.writeUInt16BE(0xbeef, 2);
console.log(buf);
// Prints: <Buffer de ad be ef>
buf.writeUInt16LE(0xdead, 0);
buf.writeUInt16LE(0xbeef, 2);
console.log(buf);
// Prints: <Buffer ad de ef be>
</code></pre>
<h3>buf.writeUInt32BE(value, offset[, noAssert])<span><a class="mark" href="#buffer_buf_writeuint32be_value_offset_noassert" id="buffer_buf_writeuint32be_value_offset_noassert">#</a></span></h3>
<h3>buf.writeUInt32LE(value, offset[, noAssert])<span><a class="mark" href="#buffer_buf_writeuint32le_value_offset_noassert" id="buffer_buf_writeuint32le_value_offset_noassert">#</a></span></h3>
<div class="signature"><ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Bytes to be written to Buffer</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> <code>0 <= offset <= buf.length - 4</code></li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Default: false</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> The offset plus the number of written bytes</li>
</ul>
</div><p>Writes <code>value</code> to the Buffer at the specified <code>offset</code> with specified endian
format (<code>writeUInt32BE()</code> writes big endian, <code>writeUInt32LE()</code> writes little
endian). The <code>value</code> should be a valid unsigned 32-bit integer. Behavior is
not defined when <code>value</code> is anything other than an unsigned 32-bit integer.</p>
<p>Set <code>noAssert</code> to true to skip validation of <code>value</code> and <code>offset</code>. This means
that <code>value</code> may be too large for the specific function and <code>offset</code> may be
beyond the end of the Buffer leading to the values being silently dropped. This
should not be used unless you are certain of correctness.</p>
<p>Example:</p>
<pre><code class="lang-js">const buf = new Buffer(4);
buf.writeUInt32BE(0xfeedface, 0);
console.log(buf);
// Prints: <Buffer fe ed fa ce>
buf.writeUInt32LE(0xfeedface, 0);
console.log(buf);
// Prints: <Buffer ce fa ed fe>
</code></pre>
<h3>buf.writeUIntBE(value, offset, byteLength[, noAssert])<span><a class="mark" href="#buffer_buf_writeuintbe_value_offset_bytelength_noassert" id="buffer_buf_writeuintbe_value_offset_bytelength_noassert">#</a></span></h3>
<h3>buf.writeUIntLE(value, offset, byteLength[, noAssert])<span><a class="mark" href="#buffer_buf_writeuintle_value_offset_bytelength_noassert" id="buffer_buf_writeuintle_value_offset_bytelength_noassert">#</a></span></h3>
<div class="signature"><ul>
<li><code>value</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Bytes to be written to Buffer</li>
<li><code>offset</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> <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"><Number></a> <code>0 < byteLength <= 6</code></li>
<li><code>noAssert</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Default: false</li>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> The offset plus the number of written bytes</li>
</ul>
</div><p>Writes <code>value</code> to the Buffer at the specified <code>offset</code> and <code>byteLength</code>.
Supports up to 48 bits of accuracy. For example:</p>
<pre><code class="lang-js">const buf = new Buffer(6);
buf.writeUIntBE(0x1234567890ab, 0, 6);
console.log(buf);
// Prints: <Buffer 12 34 56 78 90 ab>
</code></pre>
<p>Set <code>noAssert</code> to true to skip validation of <code>value</code> and <code>offset</code>. This means
that <code>value</code> may be too large for the specific function and <code>offset</code> may be
beyond the end of the Buffer leading to the values being silently dropped. This
should not be used unless you are certain of correctness.</p>
<p>Behavior is not defined when <code>value</code> is anything other than an unsigned integer.</p>
<h2>buffer.INSPECT_MAX_BYTES<span><a class="mark" href="#buffer_buffer_inspect_max_bytes" id="buffer_buffer_inspect_max_bytes">#</a></span></h2>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> Default: 50</li>
</ul>
</div><p>Returns the maximum number of bytes that will be returned when
<code>buffer.inspect()</code> is called. This can be overridden by user modules. See
<a href="util.html#util_util_inspect_object_options"><code>util.inspect()</code></a> for more details on <code>buffer.inspect()</code> behavior.</p>
<p>Note that this is a property on the <code>buffer</code> module as returned by
<code>require('buffer')</code>, not on the Buffer global or a Buffer instance.</p>
<h2>Class: SlowBuffer<span><a class="mark" href="#buffer_class_slowbuffer" id="buffer_class_slowbuffer">#</a></span></h2>
<p>Returns an un-pooled <code>Buffer</code>.</p>
<p>In order to avoid the garbage collection overhead of creating many individually
allocated Buffers, by default allocations under 4KB are sliced from a single
larger allocated object. This approach improves both performance and memory
usage since v8 does not need to track and cleanup as many <code>Persistent</code> objects.</p>
<p>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 Buffer instance using <code>SlowBuffer</code> then copy out the relevant bits.</p>
<pre><code class="lang-js">// need to keep around a few small chunks of memory
const store = [];
socket.on('readable', () => {
var data = socket.read();
// allocate for retained data
var sb = new SlowBuffer(10);
// copy the data into the new allocation
data.copy(sb, 0, 0, 10);
store.push(sb);
});
</code></pre>
<p>Use of <code>SlowBuffer</code> should be used only as a last resort <em>after</em> a developer
has observed undue memory retention in their applications.</p>
<h3>new SlowBuffer(size)<span><a class="mark" href="#buffer_new_slowbuffer_size" id="buffer_new_slowbuffer_size">#</a></span></h3>
<div class="signature"><ul>
<li><code>size</code> Number</li>
</ul>
</div><p>Allocates a new <code>SlowBuffer</code> of <code>size</code> bytes. The <code>size</code> must be less than
or equal to the value of <code>require('buffer').kMaxLength</code> (on 64-bit
architectures, <code>kMaxLength</code> is <code>(2^31)-1</code>). Otherwise, a <a href="errors.html#errors_class_rangeerror"><code>RangeError</code></a> is
thrown. If a <code>size</code> less than 0 is specified, a zero-length <code>SlowBuffer</code> will be
created.</p>
<p>The underlying memory for <code>SlowBuffer</code> instances is <em>not initialized</em>. The
contents of a newly created <code>SlowBuffer</code> are unknown and could contain
sensitive data. Use <a href="#buffer_buf_fill_value_offset_end"><code>buf.fill(0)</code></a> to initialize a <code>SlowBuffer</code> to zeroes.</p>
<pre><code class="lang-js">const SlowBuffer = require('buffer').SlowBuffer;
const buf = new SlowBuffer(5);
console.log(buf);
// <Buffer 78 e0 82 02 01>
// (octets will be different, every time)
buf.fill(0);
console.log(buf);
// <Buffer 00 00 00 00 00>
</code></pre>
<!-- [end-include:buffer.md] -->
<!-- [start-include:child_process.md] -->
<h1>Child Process<span><a class="mark" href="#child_process_child_process" id="child_process_child_process">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>The <code>child_process</code> module provides the ability to spawn child processes in
a manner that is similar, but not identical, to <a href="http://linux.die.net/man/3/popen"><code>popen(3)</code></a>. This capability
is primarily provided by the <code>child_process.spawn()</code> function:</p>
<pre><code class="lang-js">const spawn = require('child_process').spawn;
const ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
ls.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
ls.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
</code></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 child. It is possible to stream data
through these pipes in a non-blocking way. <em>Note, however, that some programs
use line-buffered I/O internally. While that does not affect Node.js, it can
mean that data sent to the child process may not be immediately consumed.</em></p>
<p>The <code>child_process.spawn()</code> method spawns the child process asynchronously,
without blocking the Node.js event loop. The <code>child_process.spawnSync()</code>
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>child_process</code> module provides a handful of synchronous
and asynchronous alternatives to <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> and
<a href="#child_process_child_process_spawnsync_command_args_options"><code>child_process.spawnSync()</code></a>. <em>Note that each of these alternatives are
implemented on top of <code>child_process.spawn()</code> or <code>child_process.spawnSync()</code>.</em></p>
<ul>
<li><code>child_process.exec()</code>: 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><code>child_process.execFile()</code>: similar to <code>child_process.exec()</code> except that
it spawns the command directly without first spawning a shell.</li>
<li><code>child_process.fork()</code>: 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><code>child_process.execSync()</code>: a synchronous version of
<code>child_process.exec()</code> that <em>will</em> block the Node.js event loop.</li>
<li><code>child_process.execFileSync()</code>: a synchronous version of
<code>child_process.execFile()</code> that <em>will</em> block the Node.js event loop.</li>
</ul>
<p>For certain use cases, such as automating shell scripts, the
<a href="#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>
<h2>Asynchronous Process Creation<span><a class="mark" href="#child_process_asynchronous_process_creation" id="child_process_asynchronous_process_creation">#</a></span></h2>
<p>The <code>child_process.spawn()</code>, <code>child_process.fork()</code>, <code>child_process.exec()</code>,
and <code>child_process.execFile()</code> methods all follow the idiomatic asynchronous
programming pattern typical of other Node.js APIs.</p>
<p>Each of the methods returns a <a href="#child_process_child_process"><code>ChildProcess</code></a> instance. These objects
implement the Node.js <a href="events.html#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 <code>child_process.exec()</code> and <code>child_process.execFile()</code> methods additionally
allow for an optional <code>callback</code> function to be specified that is invoked
when the child process terminates.</p>
<h3>Spawning <code>.bat</code> and <code>.cmd</code> files on Windows<span><a class="mark" href="#child_process_spawning_bat_and_cmd_files_on_windows" id="child_process_spawning_bat_and_cmd_files_on_windows">#</a></span></h3>
<p>The importance of the distinction between <code>child_process.exec()</code> and
<code>child_process.execFile()</code> can vary based on platform. On Unix-type operating
systems (Unix, Linux, OSX) <code>child_process.execFile()</code> can be more efficient
because it does not spawn a shell. 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 <code>child_process.execFile()</code>. When running on Windows, <code>.bat</code>
and <code>.cmd</code> files can be invoked using <code>child_process.spawn()</code> with the <code>shell</code>
option set, with <code>child_process.exec()</code>, 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
<code>child_process.exec()</code> do).</p>
<pre><code class="lang-js">// On Windows Only ...
const spawn = require('child_process').spawn;
const bat = spawn('cmd.exe', ['/c', 'my.bat']);
bat.stdout.on('data', (data) => {
console.log(data);
});
bat.stderr.on('data', (data) => {
console.log(data);
});
bat.on('exit', (code) => {
console.log(`Child exited with code ${code}`);
});
// OR...
const exec = require('child_process').exec;
exec('my.bat', (err, stdout, stderr) => {
if (err) {
console.error(err);
return;
}
console.log(stdout);
});
</code></pre>
<h3>child_process.exec(command[, options][, callback])<span><a class="mark" href="#child_process_child_process_exec_command_options_callback" id="child_process_child_process_exec_command_options_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</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> 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</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> (Default: 'utf8')</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
(Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should
understand the <code>-c</code> switch on UNIX or <code>/s /c</code> on Windows. On Windows,
command line parsing should be compatible with <code>cmd.exe</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> (Default: 0)</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 child process is killed (Default: <code>200*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> | <span class="type"><Integer></span> (Default: 'SIGTERM')</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">setuid(2)</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">setgid(2)</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 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="buffer.html#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="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li>
</ul>
</li>
<li>Returns: <a href="child_process.html#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.</p>
<p><strong>Note: Never pass unsanitised user input to this function. Any input
containing shell metacharacters may be used to trigger arbitrary command
execution.</strong></p>
<pre><code class="lang-js">const exec = require('child_process').exec;
exec('cat *.js bad_file | wc -l', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});
</code></pre>
<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="errors.html#errors_class_error"><code>Error</code></a>. The <code>error.code</code> property will be
the exit code of the child process while <code>error.signal</code> will be set to the
signal that terminated the process. Any exit code other than <code>0</code> is considered
to be an error.</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>
<p>The <code>options</code> argument may be passed as the second argument to customize how
the process is spawned. The default options are:</p>
<pre><code class="lang-js">{
encoding: 'utf8',
timeout: 0,
maxBuffer: 200*1024,
killSignal: 'SIGTERM',
cwd: null,
env: null
}
</code></pre>
<p>If <code>timeout</code> is greater than <code>0</code>, the parent will send the the signal
identified by the <code>killSignal</code> property (the default is <code>'SIGTERM'</code>) if the
child runs longer than <code>timeout</code> milliseconds.</p>
<p>The <code>maxBuffer</code> option specifies the largest amount of data (in bytes) allowed
on stdout or stderr - if this value is exceeded then the child process is
terminated.</p>
<p><em>Note: Unlike the <code>exec()</code> POSIX system call, <code>child_process.exec()</code> does not
replace the existing process and uses a shell to execute the command.</em></p>
<h3>child_process.execFile(file[, args][, options][, callback])<span><a class="mark" href="#child_process_child_process_execfile_file_args_options_callback" id="child_process_child_process_execfile_file_args_options_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.91</span>
</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/Reference/Global_Objects/Array" class="type"><Array></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> 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</li>
<li><code>encoding</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> (Default: 'utf8')</li>
<li><code>timeout</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> (Default: 0)</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 child process is killed (Default: 200*1024)</li>
<li><code>killSignal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> | <span class="type"><Integer></span> (Default: 'SIGTERM')</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">setuid(2)</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">setgid(2)</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 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="buffer.html#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="buffer.html#buffer_class_buffer" class="type"><Buffer></a></li>
</ul>
</li>
<li>Returns: <a href="child_process.html#child_process_class_childprocess" class="type"><ChildProcess></a></li>
</ul>
<p>The <code>child_process.execFile()</code> function is similar to <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a>
except that it does not spawn a shell. Rather, the specified executable <code>file</code>
is spawned directly as a new process making it slightly more efficient than
<a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a>.</p>
<p>The same options as <code>child_process.exec()</code> are supported. Since a shell is not
spawned, behaviors such as I/O redirection and file globbing are not supported.</p>
<pre><code class="lang-js">const execFile = require('child_process').execFile;
const child = execFile('node', ['--version'], (error, stdout, stderr) => {
if (error) {
throw error;
}
console.log(stdout);
});
</code></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>
<h3>child_process.fork(modulePath[, args][, options])<span><a class="mark" href="#child_process_child_process_fork_modulepath_args_options" id="child_process_child_process_fork_modulepath_args_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</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> The module to run in the child</li>
<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></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> 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</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/Reference/Global_Objects/Array" class="type"><Array></a> List of string arguments passed to the executable
(Default: <code>process.execArgv</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 true, stdin, stdout, and stderr of the child will be
piped to the parent, otherwise they will be inherited from the parent, see
the <code>'pipe'</code> and <code>'inherit'</code> options for <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a>'s
<a href="#child_process_options_stdio"><code>stdio</code></a> for more details (default is false)</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">setuid(2)</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">setgid(2)</a>.)</li>
</ul>
</li>
<li>Returns: <a href="child_process.html#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="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> used specifically to spawn new Node.js processes.
Like <code>child_process.spawn()</code>, a <code>ChildProcess</code> object is returned. The returned
<code>ChildProcess</code> 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="#child_process_child_send_message_sendhandle_callback"><code>ChildProcess#send()</code></a> for details.</p>
<p>It is important to 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
<code>process.execPath</code> 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. The input and
output on this fd is expected to be line delimited JSON objects.</p>
<p><em>Note: Unlike the <code>fork()</code> POSIX system call, <a href="child_process.html#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a> does
not clone the current process.</em></p>
<h3>child_process.spawn(command[, args][, options])<span><a class="mark" href="#child_process_child_process_spawn_command_args_options" id="child_process_child_process_spawn_command_args_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</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/Reference/Global_Objects/Array" class="type"><Array></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> 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</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="#child_process_options_stdio"><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 to run independently of its parent
process. Specific behavior depends on the platform, see
<a href="#child_process_options_detached"><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">setuid(2)</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">setgid(2)</a>.)</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
'/bin/sh' on UNIX, and 'cmd.exe' on Windows. A different shell can be
specified as a string. The shell should understand the <code>-c</code> switch on UNIX,
or <code>/s /c</code> on Windows. Defaults to <code>false</code> (no shell).</li>
</ul>
</li>
<li>Returns: <a href="child_process.html#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>Note: If the <code>shell</code> option is enabled, do not pass unsanitised 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="lang-js">{
cwd: undefined,
env: process.env
}
</code></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.</p>
<p>Use <code>env</code> to specify environment variables that will be visible to the new
process, the default is <code>process.env</code>.</p>
<p>Example of running <code>ls -lh /usr</code>, capturing <code>stdout</code>, <code>stderr</code>, and the
exit code:</p>
<pre><code class="lang-js">const spawn = require('child_process').spawn;
const ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
ls.stderr.on('data', (data) => {
console.log(`stderr: ${data}`);
});
ls.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
</code></pre>
<p>Example: A very elaborate way to run 'ps ax | grep ssh'</p>
<pre><code class="lang-js">const spawn = require('child_process').spawn;
const ps = spawn('ps', ['ax']);
const grep = spawn('grep', ['ssh']);
ps.stdout.on('data', (data) => {
grep.stdin.write(data);
});
ps.stderr.on('data', (data) => {
console.log(`ps stderr: ${data}`);
});
ps.on('close', (code) => {
if (code !== 0) {
console.log(`ps process exited with code ${code}`);
}
grep.stdin.end();
});
grep.stdout.on('data', (data) => {
console.log(`${data}`);
});
grep.stderr.on('data', (data) => {
console.log(`grep stderr: ${data}`);
});
grep.on('close', (code) => {
if (code !== 0) {
console.log(`grep process exited with code ${code}`);
}
});
</code></pre>
<p>Example of checking for failed exec:</p>
<pre><code class="lang-js">const spawn = require('child_process').spawn;
const child = spawn('bad_command');
child.on('error', (err) => {
console.log('Failed to start child process.');
});
</code></pre>
<h4>options.detached<span><a class="mark" href="#child_process_options_detached" id="child_process_options_detached">#</a></span></h4>
<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 will have
its own console window. <em>Once enabled for a child process, it cannot be
disabled</em>.</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. Note that
child processes may continue running after the parent exits regardless of
whether they are detached or not. See <code>setsid(2)</code> for more information.</p>
<p>By default, the parent will wait for the detached child to exit. To prevent
the parent from waiting for a given <code>child</code>, use the <code>child.unref()</code> method.
Doing so will cause the parent's event loop to not include the child in its
reference count, allowing the parent to exit independently of the child, unless
there is an established IPC channel between the child and parent.</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's <code>stdio</code> is inherited, the child 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><code class="lang-js">const spawn = require('child_process').spawn;
const child = spawn(process.argv[0], ['child_program.js'], {
detached: true,
stdio: 'ignore'
});
child.unref();
</code></pre>
<p>Alternatively one can redirect the child process' output into files:</p>
<pre><code class="lang-js">const fs = require('fs');
const spawn = require('child_process').spawn;
const out = fs.openSync('./out.log', 'a');
const err = fs.openSync('./out.log', 'a');
const child = spawn('prg', [], {
detached: true,
stdio: [ 'ignore', out, err ]
});
child.unref();
</code></pre>
<h4>options.stdio<span><a class="mark" href="#child_process_options_stdio" id="child_process_options_stdio">#</a></span></h4>
<div class="api_metadata">
<span>Added in: v0.7.10</span>
</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 <code>child.stdin</code>, <code>child.stdout</code>, and
<code>child.stderr</code> streams on the <code>ChildProcess</code> 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>'ignore'</code> - equivalent to <code>['ignore', 'ignore', 'ignore']</code></li>
<li><code>'inherit'</code> - equivalent to <code>[process.stdin, process.stdout, process.stderr]</code>
or <code>[0,1,2]</code></li>
</ul>
<p>Otherwise, the value of <code>option.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><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 <code>ChildProcess.stdio[fd]</code>. Pipes created for
fds 0 - 2 are also available as ChildProcess.stdin, ChildProcess.stdout
and ChildProcess.stderr, respectively.</li>
<li><code>'ipc'</code> - Create an IPC channel for passing messages/file descriptors
between parent and child. A ChildProcess may have at most <em>one</em> IPC stdio
file descriptor. Setting this option enables the ChildProcess.send() method.
If the child writes JSON messages to this file descriptor, the
<code>ChildProcess.on('message')</code> event handler will be triggered in the parent.
If the child is a Node.js process, the presence of an IPC channel will enable
<code>process.send()</code>, <code>process.disconnect()</code>, <code>process.on('disconnect')</code>, and
<code>process.on('message')</code> within the child.</li>
<li><code>'ignore'</code> - Instructs Node.js to ignore the fd in the child. While Node.js
will always open fds 0 - 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.</li>
<li><code>Stream</code> 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. Note that the stream must
have an underlying descriptor (file streams do not until the <code>'open'</code>
event has occurred).</li>
<li>Positive integer - The integer value is interpreted as a file descriptor
that is is currently open in the parent process. It is shared with the child
process, similar to how <code>Stream</code> objects can be shared.</li>
<li><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>.</li>
</ol>
<p>Example:</p>
<pre><code class="lang-js">const spawn = require('child_process').spawn;
// Child will use parent's stdios
spawn('prg', [], { stdio: 'inherit' });
// Spawn child sharing only stderr
spawn('prg', [], { stdio: ['pipe', 'pipe', process.stderr] });
// Open an extra fd=4, to interact with programs presenting a
// startd-style interface.
spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });
</code></pre>
<p><em>It is worth noting that when an IPC channel is established between the
parent and child processes, and the child is a Node.js process, the child
is launched with the IPC channel unreferenced (using <code>unref()</code>) until the
child registers an event handler for the <code>process.on('disconnect')</code> event
or the <code>process.on('message')</code> event.This allows the child to exit normally
without the process being held open by the open IPC channel.</em></p>
<p>See also: <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a> and <a href="child_process.html#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a></p>
<h2>Synchronous Process Creation<span><a class="mark" href="#child_process_synchronous_process_creation" id="child_process_synchronous_process_creation">#</a></span></h2>
<p>The <code>child_process.spawnSync()</code>, <code>child_process.execSync()</code>, and
<code>child_process.execFileSync()</code> methods are <strong>synchronous</strong> and <strong>WILL</strong> 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>
<h3>child_process.execFileSync(file[, args][, options])<span><a class="mark" href="#child_process_child_process_execfilesync_file_args_options" id="child_process_child_process_execfilesync_file_args_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.12</span>
</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/Reference/Global_Objects/Array" class="type"><Array></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> 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="buffer.html#buffer_class_buffer" class="type"><Buffer></a> The value which will be passed as stdin to the spawned process<ul>
<li>supplying this value will override <code>stdio[0]</code></li>
</ul>
</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. (Default: 'pipe')<ul>
<li><code>stderr</code> by default will be output to the parent process' stderr unless
<code>stdio</code> is specified</li>
</ul>
</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</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">setuid(2)</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">setgid(2)</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. (Default: undefined)</li>
<li><code>killSignal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> | <span class="type"><Integer></span> The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM')</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 child process is killed</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. (Default: 'buffer')</li>
</ul>
</li>
<li>Returns: <a href="buffer.html#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
<code>child_process.execFile()</code> 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. <em>Note that 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.</em></p>
<p>If the process times out, or has a non-zero exit code, this method <strong><em>will</em></strong>
throw. The <a href="errors.html#errors_class_error"><code>Error</code></a> object will contain the entire result from
<a href="#child_process_child_process_spawnsync_command_args_options"><code>child_process.spawnSync()</code></a></p>
<h3>child_process.execSync(command[, options])<span><a class="mark" href="#child_process_child_process_execsync_command_options" id="child_process_child_process_execsync_command_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.12</span>
</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> 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="buffer.html#buffer_class_buffer" class="type"><Buffer></a> The value which will be passed as stdin to the spawned process<ul>
<li>supplying this value will override <code>stdio[0]</code></li>
</ul>
</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. (Default: 'pipe')<ul>
<li><code>stderr</code> by default will be output to the parent process' stderr unless
<code>stdio</code> is specified</li>
</ul>
</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</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
(Default: '/bin/sh' on UNIX, 'cmd.exe' on Windows, The shell should
understand the <code>-c</code> switch on UNIX or <code>/s /c</code> on Windows. On Windows,
command line parsing should be compatible with <code>cmd.exe</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">setuid(2)</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">setgid(2)</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. (Default: undefined)</li>
<li><code>killSignal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> | <span class="type"><Integer></span> The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM')</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 child process is killed</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. (Default: 'buffer')</li>
</ul>
</li>
<li>Returns: <a href="buffer.html#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
<code>child_process.exec()</code> 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. <em>Note that 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.</em></p>
<p>If the process times out, or has a non-zero exit code, this method <strong><em>will</em></strong>
throw. The <a href="errors.html#errors_class_error"><code>Error</code></a> object will contain the entire result from
<a href="#child_process_child_process_spawnsync_command_args_options"><code>child_process.spawnSync()</code></a></p>
<p><strong>Note: Never pass unsanitised user input to this function. Any input
containing shell metacharacters may be used to trigger arbitrary command
execution.</strong></p>
<h3>child_process.spawnSync(command[, args][, options])<span><a class="mark" href="#child_process_child_process_spawnsync_command_args_options" id="child_process_child_process_spawnsync_command_args_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.12</span>
</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/Reference/Global_Objects/Array" class="type"><Array></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> 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="buffer.html#buffer_class_buffer" class="type"><Buffer></a> The value which will be passed as stdin to the spawned process<ul>
<li>supplying this value will override <code>stdio[0]</code></li>
</ul>
</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. (Default: 'pipe')</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</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">setuid(2)</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">setgid(2)</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. (Default: undefined)</li>
<li><code>killSignal</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> | <span class="type"><Integer></span> The signal value to be used when the spawned process will be killed. (Default: 'SIGTERM')</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 child process is killed</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. (Default: 'buffer')</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
'/bin/sh' on UNIX, and 'cmd.exe' on Windows. A different shell can be
specified as a string. The shell should understand the <code>-c</code> switch on UNIX,
or <code>/s /c</code> on Windows. Defaults to <code>false</code> (no shell).</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="buffer.html#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="buffer.html#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> The exit code of the child process</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 used to kill the child process</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
<code>child_process.spawn()</code> 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. Note that 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>Note: If the <code>shell</code> option is enabled, do not pass unsanitised user input to
this function. Any input containing shell metacharacters may be used to
trigger arbitrary command execution.</strong></p>
<h2>Class: ChildProcess<span><a class="mark" href="#child_process_class_childprocess" id="child_process_class_childprocess">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v2.2.0</span>
</div><p>Instances of the <code>ChildProcess</code> class are <a href="events.html#events_class_events_eventemitter"><code>EventEmitters</code></a> that represent
spawned child processes.</p>
<p>Instances of <code>ChildProcess</code> are not intended to be created directly. Rather,
use the <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a>, <a href="#child_process_child_process_exec_command_options_callback"><code>child_process.exec()</code></a>,
<a href="#child_process_child_process_execfile_file_args_options_callback"><code>child_process.execFile()</code></a>, or <a href="child_process.html#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a> methods to create
instances of <code>ChildProcess</code>.</p>
<h3>Event: 'close'<span><a class="mark" href="#child_process_event_close" id="child_process_event_close">#</a></span></h3>
<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 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 when the stdio streams of a child process have
been closed. This is distinct from the <code>'exit'</code> event, since multiple
processes might share the same stdio streams.</p>
<h3>Event: 'disconnect'<span><a class="mark" href="#child_process_event_disconnect" id="child_process_event_disconnect">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.2</span>
</div><p>The <code>'disconnect'</code> event is emitted after calling the
<code>ChildProcess.disconnect()</code> method in the parent or child process. After
disconnecting it is no longer possible to send or receive messages, and the
<code>ChildProcess.connected</code> property is false.</p>
<h3>Event: 'error'<span><a class="mark" href="#child_process_event_error" id="child_process_event_error">#</a></span></h3>
<div class="signature"><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>
</div><p>The <code>'error'</code> event is emitted whenever:</p>
<ol>
<li>The process could not be spawned, or</li>
<li>The process could not be killed, or</li>
<li>Sending a message to the child process failed.</li>
</ol>
<p>Note that the <code>'exit'</code> event may or may not fire after an error has occurred.
If you are listening to both the <code>'exit'</code> and <code>'error'</code> events, it is important
to guard against accidentally invoking handler functions multiple times.</p>
<p>See also <a href="#child_process_child_kill_signal"><code>ChildProcess#kill()</code></a> and <a href="#child_process_child_send_message_sendhandle_callback"><code>ChildProcess#send()</code></a>.</p>
<h3>Event: 'exit'<span><a class="mark" href="#child_process_event_exit" id="child_process_event_exit">#</a></span></h3>
<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 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-null.</p>
<p>Note that when the <code>'exit'</code> event is triggered, child process stdio streams
might still be open.</p>
<p>Also, note that 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 <code>waitpid(2)</code>.</p>
<h3>Event: 'message'<span><a class="mark" href="#child_process_event_message" id="child_process_event_message">#</a></span></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> a parsed JSON object or primitive value.</li>
<li><code>sendHandle</code> <a href="net.html#net_server_listen_handle_backlog_callback" class="type"><Handle></a> a <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> or <a href="net.html#net_class_net_server"><code>net.Server</code></a> object, or
undefined.</li>
</ul>
<p>The <code>'message'</code> event is triggered when a child process uses <code>process.send()</code>
to send messages.</p>
<h3>child.connected<span><a class="mark" href="#child_process_child_connected" id="child_process_child_connected">#</a></span></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> Set to false after <code>.disconnect</code> is called</li>
</ul>
<p>The <code>child.connected</code> property indicates whether it is still possible to send
and receive messages from a child process. When <code>child.connected</code> is false, it
is no longer possible to send or receive messages.</p>
<h3>child.disconnect()<span><a class="mark" href="#child_process_child_disconnect" id="child_process_child_disconnect">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.2</span>
</div><p>Closes the IPC channel between parent and child, allowing the child to exit
gracefully once there are no other connections keeping it alive. After calling
this method the <code>child.connected</code> and <code>process.connected</code> properties in both
the parent and child (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>child.disconnect()</code>.</p>
<p>Note that when the child process is a Node.js instance (e.g. spawned using
<a href="child_process.html#child_process_child_process_fork_modulepath_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>
<h3>child.kill([signal])<span><a class="mark" href="#child_process_child_kill_signal" id="child_process_child_kill_signal">#</a></span></h3>
<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#String_type" class="type"><String></a></li>
</ul>
<p>The <code>child.kill()</code> methods 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">signal(7)</a> for
a list of available signals.</p>
<pre><code class="lang-js">const spawn = require('child_process').spawn;
const grep = spawn('grep', ['ssh']);
grep.on('close', (code, signal) => {
console.log(
`child process terminated due to receipt of signal ${signal}`);
});
// Send SIGHUP to process
grep.kill('SIGHUP');
</code></pre>
<p>The <code>ChildProcess</code> object may emit an <code>'error'</code> 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>Note that while the function is called <code>kill</code>, the signal delivered to the
child process may not actually terminate the process.</p>
<p>See <code>kill(2)</code> for reference.</p>
<p>Also note: 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 use of the <code>shell</code> option of <code>ChildProcess</code>, such
as in this example:</p>
<pre><code class="lang-js">'use strict';
const spawn = require('child_process').spawn;
let child = spawn('sh', ['-c',
`node -e "setInterval(() => {
console.log(process.pid, 'is alive')
}, 500);"`
], {
stdio: ['inherit', 'inherit', 'inherit']
});
setTimeout(() => {
child.kill(); // does not terminate the node process in the shell
}, 2000);
</code></pre>
<h3>child.pid<span><a class="mark" href="#child_process_child_pid" id="child_process_child_pid">#</a></span></h3>
<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"><Number></a> Integer</li>
</ul>
<p>Returns the process identifier (PID) of the child process.</p>
<p>Example:</p>
<pre><code class="lang-js">const spawn = require('child_process').spawn;
const grep = spawn('grep', ['ssh']);
console.log(`Spawned child pid: ${grep.pid}`);
grep.stdin.end();
</code></pre>
<h3>child.send(message[, sendHandle][, callback])<span><a class="mark" href="#child_process_child_send_message_sendhandle_callback" id="child_process_child_send_message_sendhandle_callback">#</a></span></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="net.html#net_server_listen_handle_backlog_callback" class="type"><Handle></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>When an IPC channel has been established between the parent and child (
i.e. when using <a href="child_process.html#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>), the <code>child.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 <code>process.on('message')</code> event.</p>
<p>For example, in the parent script:</p>
<pre><code class="lang-js">const cp = require('child_process');
const n = cp.fork(`${__dirname}/sub.js`);
n.on('message', (m) => {
console.log('PARENT got message:', m);
});
n.send({ hello: 'world' });
</code></pre>
<p>And then the child script, <code>'sub.js'</code> might look like this:</p>
<pre><code class="lang-js">process.on('message', (m) => {
console.log('CHILD got message:', m);
});
process.send({ foo: 'bar' });
</code></pre>
<p>Child Node.js processes will have a <code>process.send()</code> method of their own that
allows the child to send messages back to the parent.</p>
<p>There is a special case when sending a <code>{cmd: 'NODE_foo'}</code> message. All messages
containing a <code>NODE_</code> prefix in its <code>cmd</code> property are considered to be reserved
for use within Node.js core and will not be emitted in the child's
<code>process.on('message')</code> event. Rather, such messages are emitted using the
<code>process.on('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>child.send()</code> is for
passing a TCP server or socket object to the child process. The child will
receive the object as the second argument passed to the callback function
registered on the <code>process.on('message')</code> event. Any data that is received and
buffered in the socket will not be sent to the child.</p>
<p>The optional <code>callback</code> is a function that is invoked after the message is
sent but before the child may have received it. The function is called with a
single argument: <code>null</code> on success, or an <a href="errors.html#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 <code>ChildProcess</code> object. This can happen,
for instance, when the child process has already exited.</p>
<p><code>child.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>
<h4>Example: sending a server object<span><a class="mark" href="#child_process_example_sending_a_server_object" id="child_process_example_sending_a_server_object">#</a></span></h4>
<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><code class="lang-js">const child = require('child_process').fork('child.js');
// Open up the server object and send the handle.
const server = require('net').createServer();
server.on('connection', (socket) => {
socket.end('handled by parent');
});
server.listen(1337, () => {
child.send('server', server);
});
</code></pre>
<p>The child would then receive the server object as:</p>
<pre><code class="lang-js">process.on('message', (m, server) => {
if (m === 'server') {
server.on('connection', (socket) => {
socket.end('handled by child');
});
}
});
</code></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>net</code> module, <code>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, currently only supported on UNIX platforms.</p>
<h4>Example: sending a socket object<span><a class="mark" href="#child_process_example_sending_a_socket_object" id="child_process_example_sending_a_socket_object">#</a></span></h4>
<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><code class="lang-js">const normal = require('child_process').fork('child.js', ['normal']);
const special = require('child_process').fork('child.js', ['special']);
// Open up the server and send sockets to child
const server = require('net').createServer();
server.on('connection', (socket) => {
// If this is special priority
if (socket.remoteAddress === '74.125.127.100') {
special.send('socket', socket);
return;
}
// This is normal priority
normal.send('socket', socket);
});
server.listen(1337);
</code></pre>
<p>The <code>child.js</code> would receive the socket handle as the second argument passed
to the event callback function:</p>
<pre><code class="lang-js">process.on('message', (m, socket) => {
if (m === 'socket') {
socket.end(`Request handled with ${process.argv[2]} priority`);
}
});
</code></pre>
<p>Once a socket has been passed to a child, the parent is no longer capable of
tracking when the socket is destroyed. To indicate this, the <code>.connections</code>
property becomes <code>null</code>. It is recommended not to use <code>.maxConnections</code> when
this occurs.</p>
<p><em>Note: this function uses <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify"><code>JSON.stringify()</code></a> internally to serialize the <code>message</code>.</em></p>
<h3>child.stderr<span><a class="mark" href="#child_process_child_stderr" id="child_process_child_stderr">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><ul>
<li><a href="stream.html#stream_stream" class="type"><Stream></a></li>
</ul>
<p>A <code>Readable Stream</code> that represents the child process's <code>stderr</code>.</p>
<p>If the child was spawned with <code>stdio[2]</code> set to anything other than <code>'pipe'</code>,
then this will be <code>undefined</code>.</p>
<p><code>child.stderr</code> is an alias for <code>child.stdio[2]</code>. Both properties will refer to
the same value.</p>
<h3>child.stdin<span><a class="mark" href="#child_process_child_stdin" id="child_process_child_stdin">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><ul>
<li><a href="stream.html#stream_stream" class="type"><Stream></a></li>
</ul>
<p>A <code>Writable Stream</code> that represents the child process's <code>stdin</code>.</p>
<p><em>Note that if a child process waits to read all of its input, the child will not
continue until this stream has been closed via <code>end()</code>.</em></p>
<p>If the child was spawned with <code>stdio[0]</code> set to anything other than <code>'pipe'</code>,
then this will be <code>undefined</code>.</p>
<p><code>child.stdin</code> is an alias for <code>child.stdio[0]</code>. Both properties will refer to
the same value.</p>
<h3>child.stdio<span><a class="mark" href="#child_process_child_stdio" id="child_process_child_stdio">#</a></span></h3>
<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="#child_process_options_stdio"><code>stdio</code></a> option passed to <a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn()</code></a> that have been set
to the value <code>'pipe'</code>. Note that <code>child.stdio[0]</code>, <code>child.stdio[1]</code>, and
<code>child.stdio[2]</code> are also available as <code>child.stdin</code>, <code>child.stdout</code>, and
<code>child.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>child.stdio[1]</code> is a stream, all other values in
the array are <code>null</code>.</p>
<pre><code class="lang-js">const assert = require('assert');
const fs = require('fs');
const child_process = require('child_process');
const child = child_process.spawn('ls', {
stdio: [
0, // Use parents stdin for child
'pipe', // Pipe child's stdout to parent
fs.openSync('err.out', 'w') // Direct child's stderr to a file
]
});
assert.equal(child.stdio[0], null);
assert.equal(child.stdio[0], child.stdin);
assert(child.stdout);
assert.equal(child.stdio[1], child.stdout);
assert.equal(child.stdio[2], null);
assert.equal(child.stdio[2], child.stderr);
</code></pre>
<h3>child.stdout<span><a class="mark" href="#child_process_child_stdout" id="child_process_child_stdout">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><ul>
<li><a href="stream.html#stream_stream" class="type"><Stream></a></li>
</ul>
<p>A <code>Readable Stream</code> that represents the child process's <code>stdout</code>.</p>
<p>If the child was spawned with <code>stdio[1]</code> set to anything other than <code>'pipe'</code>,
then this will be <code>undefined</code>.</p>
<p><code>child.stdout</code> is an alias for <code>child.stdio[1]</code>. Both properties will refer
to the same value.</p>
<!-- [end-include:child_process.md] -->
<!-- [start-include:cluster.md] -->
<h1>Cluster<span><a class="mark" href="#cluster_cluster" id="cluster_cluster">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>A single instance of Node.js runs in a single thread. To take advantage of
multi-core systems the user will sometimes want to launch a cluster of Node.js
processes to handle the load.</p>
<p>The cluster module allows you to easily create child processes that
all share server ports.</p>
<pre><code class="lang-js">const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
// Workers can share any TCP connection
// In this case it is an HTTP server
http.createServer((req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
}
</code></pre>
<p>Running Node.js will now share port 8000 between the workers:</p>
<pre><code>$ NODE_DEBUG=cluster node server.js
23521,Master Worker 23524 online
23521,Master Worker 23526 online
23521,Master Worker 23523 online
23521,Master Worker 23528 online
</code></pre><p>Please note that, on Windows, it is not yet possible to set up a named pipe
server in a worker.</p>
<h2>How It Works<span><a class="mark" href="#cluster_how_it_works" id="cluster_how_it_works">#</a></span></h2>
<!--type=misc-->
<p>The worker processes are spawned using the <a href="child_process.html#child_process_child_process_fork_modulepath_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 master 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 master 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 master
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 master,
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 master
process. If the worker already has the handle, then it's presumed
that you know what you are doing.</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. If you
want to listen on a unique port, generate a port number based on the
cluster worker ID.</li>
</ol>
<p>There is no routing logic in Node.js, or in your program, and no shared
state between the workers. Therefore, it is important to design your
program 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 your 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 for you, however. It is your
responsibility to manage the worker pool for your application's needs.</p>
<h2>Class: Worker<span><a class="mark" href="#cluster_class_worker" id="cluster_class_worker">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div><p>A Worker object contains all public information and method about a worker.
In the master it can be obtained using <code>cluster.workers</code>. In a worker
it can be obtained using <code>cluster.worker</code>.</p>
<h3>Event: 'disconnect'<span><a class="mark" href="#cluster_event_disconnect" id="cluster_event_disconnect">#</a></span></h3>
<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="lang-js">cluster.fork().on('disconnect', () => {
// Worker has disconnected
});
</code></pre>
<h3>Event: 'error'<span><a class="mark" href="#cluster_event_error" id="cluster_event_error">#</a></span></h3>
<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="child_process.html#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>.</p>
<p>In a worker you can also use <code>process.on('error')</code>.</p>
<h3>Event: 'exit'<span><a class="mark" href="#cluster_event_exit" id="cluster_event_exit">#</a></span></h3>
<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><code class="lang-js">const worker = cluster.fork();
worker.on('exit', (code, signal) => {
if (signal) {
console.log(`worker was killed by signal: ${signal}`);
} else if (code !== 0) {
console.log(`worker exited with error code: ${code}`);
} else {
console.log('worker success!');
}
});
</code></pre>
<h3>Event: 'listening'<span><a class="mark" href="#cluster_event_listening" id="cluster_event_listening">#</a></span></h3>
<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><code class="lang-js">cluster.fork().on('listening', (address) => {
// Worker is listening
});
</code></pre>
<p>It is not emitted in the worker.</p>
<h3>Event: 'message'<span><a class="mark" href="#cluster_event_message" id="cluster_event_message">#</a></span></h3>
<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> <span class="type"><undefined></span> | <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('message')</code> event, but specific to this worker. In a
worker you can also use <code>process.on('message')</code>.</p>
<p>See <a href="process.html#process_event_message"><code>process</code> event: <code>'message'</code></a>.</p>
<p>As an example, here is a cluster that keeps count of the number of requests
in the master process using the message system:</p>
<pre><code class="lang-js">const cluster = require('cluster');
const http = require('http');
if (cluster.isMaster) {
// Keep track of http requests
var numReqs = 0;
setInterval(() => {
console.log('numReqs =', numReqs);
}, 1000);
// Count requests
function messageHandler(msg) {
if (msg.cmd && msg.cmd == 'notifyRequest') {
numReqs += 1;
}
}
// Start workers and listen for messages containing notifyRequest
const numCPUs = require('os').cpus().length;
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
Object.keys(cluster.workers).forEach((id) => {
cluster.workers[id].on('message', messageHandler);
});
} else {
// Worker processes have a http server.
http.Server((req, res) => {
res.writeHead(200);
res.end('hello world\n');
// notify master about the request
process.send({ cmd: 'notifyRequest' });
}).listen(8000);
}
</code></pre>
<h3>Event: 'online'<span><a class="mark" href="#cluster_event_online" id="cluster_event_online">#</a></span></h3>
<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="lang-js">cluster.fork().on('online', () => {
// Worker is online
});
</code></pre>
<p>It is not emitted in the worker.</p>
<h3>worker.disconnect()<span><a class="mark" href="#cluster_worker_disconnect" id="cluster_worker_disconnect">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div><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 master, an internal message is sent to the worker causing it to call
<code>.disconnect()</code> on itself.</p>
<p>Causes <code>.suicide</code> to be set.</p>
<p>Note that 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="#net_server_close_callback"><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>Note that in a worker, <code>process.disconnect</code> exists, but it is not this function,
it is <a href="child_process.html#child_process_child_disconnect"><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="lang-js">if (cluster.isMaster) {
var worker = cluster.fork();
var timeout;
worker.on('listening', (address) => {
worker.send('shutdown');
worker.disconnect();
timeout = setTimeout(() => {
worker.kill();
}, 2000);
});
worker.on('disconnect', () => {
clearTimeout(timeout);
});
} else if (cluster.isWorker) {
const net = require('net');
var server = net.createServer((socket) => {
// connections never end
});
server.listen(8000);
process.on('message', (msg) => {
if (msg === 'shutdown') {
// initiate graceful close of any connections to server
}
});
}
</code></pre>
<h3>worker.id<span><a class="mark" href="#cluster_worker_id" id="cluster_worker_id">#</a></span></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#Number_type" class="type"><Number></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
cluster.workers</p>
<h3>worker.isConnected()<span><a class="mark" href="#cluster_worker_isconnected" id="cluster_worker_isconnected">#</a></span></h3>
<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 master via its IPC
channel, <code>false</code> otherwise. A worker is connected to its master after it's been
created. It is disconnected after the <code>'disconnect'</code> event is emitted.</p>
<h3>worker.isDead()<span><a class="mark" href="#cluster_worker_isdead" id="cluster_worker_isdead">#</a></span></h3>
<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>
<h3>worker.kill([signal='SIGTERM'])<span><a class="mark" href="#cluster_worker_kill_signal_sigterm" id="cluster_worker_kill_signal_sigterm">#</a></span></h3>
<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.</li>
</ul>
<p>This function will kill the worker. In the master, 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 disconnecting the channel, and then exiting with code <code>0</code>.</p>
<p>Causes <code>.suicide</code> to be set.</p>
<p>This method is aliased as <code>worker.destroy()</code> for backwards compatibility.</p>
<p>Note that in a worker, <code>process.kill()</code> exists, but it is not this function,
it is <a href="process.html#process_process_kill_pid_signal"><code>kill</code></a>.</p>
<h3>worker.process<span><a class="mark" href="#cluster_worker_process" id="cluster_worker_process">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div><ul>
<li><a href="child_process.html#child_process_class_childprocess" class="type"><ChildProcess></a></li>
</ul>
<p>All workers are created using <a href="child_process.html#child_process_child_process_fork_modulepath_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="child_process.html#child_process_child_process_fork_modulepath_args_options">Child Process module</a></p>
<p>Note that workers will call <code>process.exit(0)</code> if the <code>'disconnect'</code> event occurs
on <code>process</code> and <code>.suicide</code> is not <code>true</code>. This protects against accidental
disconnection.</p>
<h3>worker.send(message[, sendHandle][, callback])<span><a class="mark" href="#cluster_worker_send_message_sendhandle_callback" id="cluster_worker_send_message_sendhandle_callback">#</a></span></h3>
<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>sendHandle</code> <a href="net.html#net_server_listen_handle_backlog_callback" class="type"><Handle></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: Boolean</li>
</ul>
<p>Send a message to a worker or master, optionally with a handle.</p>
<p>In the master this sends a message to a specific worker. It is identical to
<a href="child_process.html#child_process_child_send_message_sendhandle_callback"><code>ChildProcess.send()</code></a>.</p>
<p>In a worker this sends a message to the master. It is identical to
<code>process.send()</code>.</p>
<p>This example will echo back all messages from the master:</p>
<pre><code class="lang-js">if (cluster.isMaster) {
var worker = cluster.fork();
worker.send('hi there');
} else if (cluster.isWorker) {
process.on('message', (msg) => {
process.send(msg);
});
}
</code></pre>
<h3>worker.suicide<span><a class="mark" href="#cluster_worker_suicide" id="cluster_worker_suicide">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
<span>Deprecated since: 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>Set by calling <code>.kill()</code> or <code>.disconnect()</code>, until then it is <code>undefined</code>.</p>
<p>The boolean <code>worker.suicide</code> lets you distinguish between voluntary and accidental
exit, the master may choose not to respawn a worker based on this value.</p>
<pre><code class="lang-js">cluster.on('exit', (worker, code, signal) => {
if (worker.suicide === true) {
console.log('Oh, it was just suicide\' – no need to worry').
}
});
// kill worker
worker.kill();
</code></pre>
<h2>Event: 'disconnect'<span><a class="mark" href="#cluster_event_disconnect_1" id="cluster_event_disconnect_1">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.9</span>
</div><ul>
<li><code>worker</code> <a href="cluster.html#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
worker.disconnect()).</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="lang-js">cluster.on('disconnect', (worker) => {
console.log(`The worker #${worker.id} has disconnected`);
});
</code></pre>
<h2>Event: 'exit'<span><a class="mark" href="#cluster_event_exit_1" id="cluster_event_exit_1">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.9</span>
</div><ul>
<li><code>worker</code> <a href="cluster.html#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 <code>.fork()</code> again.</p>
<pre><code class="lang-js">cluster.on('exit', (worker, code, signal) => {
console.log('worker %d died (%s). restarting...',
worker.process.pid, signal || code);
cluster.fork();
});
</code></pre>
<p>See <a href="child_process.html#child_process_event_exit">child_process event: 'exit'</a>.</p>
<h2>Event: 'fork'<span><a class="mark" href="#cluster_event_fork" id="cluster_event_fork">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div><ul>
<li><code>worker</code> <a href="cluster.html#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 your own timeout.</p>
<pre><code class="lang-js">var timeouts = [];
function errorMsg() {
console.error('Something must be wrong with the connection ...');
}
cluster.on('fork', (worker) => {
timeouts[worker.id] = setTimeout(errorMsg, 2000);
});
cluster.on('listening', (worker, address) => {
clearTimeout(timeouts[worker.id]);
});
cluster.on('exit', (worker, code, signal) => {
clearTimeout(timeouts[worker.id]);
errorMsg();
});
</code></pre>
<h2>Event: 'listening'<span><a class="mark" href="#cluster_event_listening_1" id="cluster_event_listening_1">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div><ul>
<li><code>worker</code> <a href="cluster.html#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 master.</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="lang-js">cluster.on('listening', (worker, address) => {
console.log(
`A worker is now connected to ${address.address}:${address.port}`);
});
</code></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> (UDP v4 or v6)</li>
</ul>
<h2>Event: 'message'<span><a class="mark" href="#cluster_event_message_1" id="cluster_event_message_1">#</a></span></h2>
<div class="signature"><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> <span class="type"><undefined></span> | <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object" class="type"><Object></a></li>
</ul>
</div><p>Emitted when the cluster master receives a message from any worker.</p>
<p>See <a href="child_process.html#child_process_event_message">child_process event: 'message'</a>.</p>
<h2>Event: 'online'<span><a class="mark" href="#cluster_event_online_1" id="cluster_event_online_1">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div><ul>
<li><code>worker</code> <a href="cluster.html#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 master 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
master forks a worker, and 'online' is emitted when the worker is running.</p>
<pre><code class="lang-js">cluster.on('online', (worker) => {
console.log('Yay, the worker responded after it was forked');
});
</code></pre>
<h2>Event: 'setup'<span><a class="mark" href="#cluster_event_setup" id="cluster_event_setup">#</a></span></h2>
<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 <code>.setupMaster()</code> is called.</p>
<p>The <code>settings</code> object is the <code>cluster.settings</code> object at the time
<code>.setupMaster()</code> was called and is advisory only, since multiple calls to
<code>.setupMaster()</code> can be made in a single tick.</p>
<p>If accuracy is important, use <code>cluster.settings</code>.</p>
<h2>cluster.disconnect([callback])<span><a class="mark" href="#cluster_cluster_disconnect_callback" id="cluster_cluster_disconnect_callback">#</a></span></h2>
<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
master 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 master process.</p>
<h2>cluster.fork([env])<span><a class="mark" href="#cluster_cluster_fork_env" id="cluster_cluster_fork_env">#</a></span></h2>
<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>return <a href="cluster.html#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 master process.</p>
<h2>cluster.isMaster<span><a class="mark" href="#cluster_cluster_ismaster" id="cluster_cluster_ismaster">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.8.1</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 master. This is determined
by the <code>process.env.NODE_UNIQUE_ID</code>. If <code>process.env.NODE_UNIQUE_ID</code> is
undefined, then <code>isMaster</code> is <code>true</code>.</p>
<h2>cluster.isWorker<span><a class="mark" href="#cluster_cluster_isworker" id="cluster_cluster_isworker">#</a></span></h2>
<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 master (it is the negation of <code>cluster.isMaster</code>).</p>
<h2>cluster.schedulingPolicy<span><a class="mark" href="#cluster_cluster_schedulingpolicy" id="cluster_cluster_schedulingpolicy">#</a></span></h2>
<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 you spawn the first worker
or call <code>cluster.setupMaster()</code>, whatever 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>
<h2>cluster.settings<span><a class="mark" href="#cluster_cluster_settings" id="cluster_cluster_settings">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.1</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>execArgv</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> list of string arguments passed to the Node.js
executable. (Default=<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. (Default=<code>process.argv[1]</code>)</li>
<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> string arguments passed to worker.
(Default=<code>process.argv.slice(2)</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.
(Default=<code>false</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">setuid(2)</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">setgid(2)</a>.)</li>
</ul>
</li>
</ul>
<p>After calling <code>.setupMaster()</code> (or <code>.fork()</code>) this settings object will contain
the settings, including the default values.</p>
<p>This object is not supposed to be changed or set manually, by you.</p>
<h2>cluster.setupMaster([settings])<span><a class="mark" href="#cluster_cluster_setupmaster_settings" id="cluster_cluster_setupmaster_settings">#</a></span></h2>
<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><ul>
<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. (Default=<code>process.argv[1]</code>)</li>
<li><code>args</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> string arguments passed to worker.
(Default=<code>process.argv.slice(2)</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.
(Default=<code>false</code>)</li>
</ul>
</li>
</ul>
<p><code>setupMaster</code> is used to change the default 'fork' behavior. Once called,
the settings will be present in <code>cluster.settings</code>.</p>
<p>Note that:</p>
<ul>
<li>any settings changes only affect future calls to <code>.fork()</code> and have no
effect on workers that are already running</li>
<li>The <em>only</em> attribute of a worker that cannot be set via <code>.setupMaster()</code> is
the <code>env</code> passed to <code>.fork()</code></li>
<li>the defaults above apply to the first call only, the defaults for later
calls is the current value at the time of <code>cluster.setupMaster()</code> is called</li>
</ul>
<p>Example:</p>
<pre><code class="lang-js">const cluster = require('cluster');
cluster.setupMaster({
exec: 'worker.js',
args: ['--use', 'https'],
silent: true
});
cluster.fork(); // https worker
cluster.setupMaster({
exec: 'worker.js',
args: ['--use', 'http']
});
cluster.fork(); // http worker
</code></pre>
<p>This can only be called from the master process.</p>
<h2>cluster.worker<span><a class="mark" href="#cluster_cluster_worker" id="cluster_cluster_worker">#</a></span></h2>
<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 master process.</p>
<pre><code class="lang-js">const cluster = require('cluster');
if (cluster.isMaster) {
console.log('I am master');
cluster.fork();
cluster.fork();
} else if (cluster.isWorker) {
console.log(`I am worker #${cluster.worker.id}`);
}
</code></pre>
<h2>cluster.workers<span><a class="mark" href="#cluster_cluster_workers" id="cluster_cluster_workers">#</a></span></h2>
<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. Makes it
easy to loop through all the workers. It is only available in the master
process.</p>
<p>A worker is removed from cluster.workers 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 cluster.workers list happens
before last <code>'disconnect'</code> or <code>'exit'</code> event is emitted.</p>
<pre><code class="lang-js">// Go through all workers
function eachWorker(callback) {
for (var id in cluster.workers) {
callback(cluster.workers[id]);
}
}
eachWorker((worker) => {
worker.send('big announcement to all workers');
});
</code></pre>
<p>Should you wish to reference a worker over a communication channel, using
the worker's unique id is the easiest way to find the worker.</p>
<pre><code class="lang-js">socket.on('data', (id) => {
var worker = cluster.workers[id];
});
</code></pre>
<!-- [end-include:cluster.md] -->
<!-- [start-include:cli.md] -->
<h1>Command Line Options<span><a class="mark" href="#cli_command_line_options" id="cli_command_line_options">#</a></span></h1>
<!--type=misc-->
<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 your terminal, run <code>man node</code>.</p>
<h2>Synopsis<span><a class="mark" href="#cli_synopsis" id="cli_synopsis">#</a></span></h2>
<p><code>node [options] [v8 options] [script.js | -e "script"] [arguments]</code></p>
<p><code>node debug [script.js | -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><em>For more info about <code>node debug</code>, please see the <a href="debugger.html">debugger</a> documentation.</em></p>
<h2>Options<span><a class="mark" href="#cli_options" id="cli_options">#</a></span></h2>
<h3><code>-v</code>, <code>--version</code><span><a class="mark" href="#cli_v_version" id="cli_v_version">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.3</span>
</div><p>Print node's version.</p>
<h3><code>-h</code>, <code>--help</code><span><a class="mark" href="#cli_h_help" id="cli_h_help">#</a></span></h3>
<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>
<h3><code>-e</code>, <code>--eval "script"</code><span><a class="mark" href="#cli_e_eval_script" id="cli_e_eval_script">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.2</span>
</div><p>Evaluate the following argument as JavaScript.</p>
<h3><code>-p</code>, <code>--print "script"</code><span><a class="mark" href="#cli_p_print_script" id="cli_p_print_script">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.6.4</span>
</div><p>Identical to <code>-e</code> but prints the result.</p>
<h3><code>-c</code>, <code>--check</code><span><a class="mark" href="#cli_c_check" id="cli_c_check">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v4.2.0</span>
</div><p>Syntax check the script without executing.</p>
<h3><code>-i</code>, <code>--interactive</code><span><a class="mark" href="#cli_i_interactive" id="cli_i_interactive">#</a></span></h3>
<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>
<h3><code>-r</code>, <code>--require module</code><span><a class="mark" href="#cli_r_require_module" id="cli_r_require_module">#</a></span></h3>
<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>
<h3><code>--no-deprecation</code><span><a class="mark" href="#cli_no_deprecation" id="cli_no_deprecation">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.8.0</span>
</div><p>Silence deprecation warnings.</p>
<h3><code>--trace-deprecation</code><span><a class="mark" href="#cli_trace_deprecation" id="cli_trace_deprecation">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.8.0</span>
</div><p>Print stack traces for deprecations.</p>
<h3><code>--throw-deprecation</code><span><a class="mark" href="#cli_throw_deprecation" id="cli_throw_deprecation">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div><p>Throw errors for deprecations.</p>
<h3><code>--trace-sync-io</code><span><a class="mark" href="#cli_trace_sync_io" id="cli_trace_sync_io">#</a></span></h3>
<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>
<h3><code>--zero-fill-buffers</code><span><a class="mark" href="#cli_zero_fill_buffers" id="cli_zero_fill_buffers">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v4.5.0</span>
</div><p>Automatically zero-fills all newly allocated <a href="buffer.html">Buffer</a> and <a href="buffer.html#buffer_class_slowbuffer">SlowBuffer</a>
instances.</p>
<h3><code>--track-heap-objects</code><span><a class="mark" href="#cli_track_heap_objects" id="cli_track_heap_objects">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v2.4.0</span>
</div><p>Track heap object allocations for heap snapshots.</p>
<h3><code>--prof-process</code><span><a class="mark" href="#cli_prof_process" id="cli_prof_process">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v4.4.0</span>
</div><p>Process v8 profiler output generated using the v8 option <code>--prof</code>.</p>
<h3><code>--v8-options</code><span><a class="mark" href="#cli_v8_options" id="cli_v8_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.3</span>
</div><p>Print v8 command line options.</p>
<h3><code>--tls-cipher-list=list</code><span><a class="mark" href="#cli_tls_cipher_list_list" id="cli_tls_cipher_list_list">#</a></span></h3>
<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>
<h3><code>--enable-fips</code><span><a class="mark" href="#cli_enable_fips" id="cli_enable_fips">#</a></span></h3>
<p>Enable FIPS-compliant crypto at startup. (Requires Node.js to be built with
<code>./configure --openssl-fips</code>)</p>
<h3><code>--force-fips</code><span><a class="mark" href="#cli_force_fips" id="cli_force_fips">#</a></span></h3>
<p>Force FIPS-compliant crypto on startup. (Cannot be disabled from script code.)
(Same requirements as <code>--enable-fips</code>)</p>
<h3><code>--icu-data-dir=file</code><span><a class="mark" href="#cli_icu_data_dir_file" id="cli_icu_data_dir_file">#</a></span></h3>
<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>
<h2>Environment Variables<span><a class="mark" href="#cli_environment_variables" id="cli_environment_variables">#</a></span></h2>
<h3><code>NODE_DEBUG=module[,…]</code><span><a class="mark" href="#cli_node_debug_module" id="cli_node_debug_module">#</a></span></h3>
<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>
<h3><code>NODE_PATH=path[:…]</code><span><a class="mark" href="#cli_node_path_path" id="cli_node_path_path">#</a></span></h3>
<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><em>Note: on Windows, this is a <code>';'</code>-separated list instead.</em></p>
<h3><code>NODE_DISABLE_COLORS=1</code><span><a class="mark" href="#cli_node_disable_colors_1" id="cli_node_disable_colors_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div><p>When set to <code>1</code> colors will not be used in the REPL.</p>
<h3><code>NODE_ICU_DATA=file</code><span><a class="mark" href="#cli_node_icu_data_file" id="cli_node_icu_data_file">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.15</span>
</div><p>Data path for ICU (Intl object) data. Will extend linked-in data when compiled
with small-icu support.</p>
<h3><code>NODE_REPL_HISTORY=file</code><span><a class="mark" href="#cli_node_repl_history_file" id="cli_node_repl_history_file">#</a></span></h3>
<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>
<h3><code>NODE_EXTRA_CA_CERTS=file</code><span><a class="mark" href="#cli_node_extra_ca_certs_file" id="cli_node_extra_ca_certs_file">#</a></span></h3>
<div class="api_metadata">
<span>Added in: XXX</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 printed to stderr (once)
if the file is missing or
misformatted, but any errors are otherwise ignored.</p>
<p>Note that 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>
<!-- [end-include:cli.md] -->
<!-- [start-include:console.md] -->
<h1>Console<span><a class="mark" href="#console_console" id="console_console">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>The <code>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 <code>stdout</code> and <code>stderr</code>.
Because this object is global, it can be used without calling
<code>require('console')</code>.</li>
</ul>
<p>Example using the global <code>console</code>:</p>
<pre><code class="lang-js">console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to stderr
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr
</code></pre>
<p>Example using the <code>Console</code> class:</p>
<pre><code class="lang-js">const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to err
</code></pre>
<p>While the API for the <code>Console</code> class is designed fundamentally around the
browser <code>console</code> object, the <code>Console</code> in Node.js is <em>not</em> intended to
duplicate the browser's functionality exactly.</p>
<h2>Asynchronous vs Synchronous Consoles<span><a class="mark" href="#console_asynchronous_vs_synchronous_consoles" id="console_asynchronous_vs_synchronous_consoles">#</a></span></h2>
<p>The console functions are usually asynchronous unless the destination is a file.
Disks are fast and operating systems normally employ write-back caching;
it should be a very rare occurrence indeed that a write blocks, but it
is possible.</p>
<p>Additionally, console functions are blocking when outputting to TTYs
(terminals) on OS X as a workaround for the OS's very small, 1kb buffer size.
This is to prevent interleaving between <code>stdout</code> and <code>stderr</code>.</p>
<h2>Class: Console<span><a class="mark" href="#console_class_console" id="console_class_console">#</a></span></h2>
<!--type=class-->
<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('console').Console</code>
or <code>console.Console</code>:</p>
<pre><code class="lang-js">const Console = require('console').Console;
const Console = console.Console;
</code></pre>
<h3>new Console(stdout[, stderr])<span><a class="mark" href="#console_new_console_stdout_stderr" id="console_new_console_stdout_stderr">#</a></span></h3>
<p>Creates a new <code>Console</code> by passing 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> isn't passed, warning and error
output will be sent to <code>stdout</code>.</p>
<pre><code class="lang-js">const output = fs.createWriteStream('./stdout.log');
const errorOutput = fs.createWriteStream('./stderr.log');
// custom simple logger
const logger = new Console(output, errorOutput);
// use it like console
const count = 5;
logger.log('count: %d', count);
// in stdout.log: count 5
</code></pre>
<p>The global <code>console</code> is a special <code>Console</code> whose output is sent to
<a href="process.html#process_process_stdout"><code>process.stdout</code></a> and <a href="process.html#process_process_stderr"><code>process.stderr</code></a>. It is equivalent to calling:</p>
<pre><code class="lang-js">new Console(process.stdout, process.stderr);
</code></pre>
<h3>console.assert(value[, message][, ...])<span><a class="mark" href="#console_console_assert_value_message" id="console_console_assert_value_message">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.101</span>
</div><p>A simple assertion test that verifies whether <code>value</code> is truthy. If it is not,
an <code>AssertionError</code> is thrown. If provided, the error <code>message</code> is formatted
using <a href="util.html#util_util_format_format"><code>util.format()</code></a> and used as the error message.</p>
<pre><code class="lang-js">console.assert(true, 'does nothing');
// OK
console.assert(false, 'Whoops %s', 'didn\'t work');
// AssertionError: Whoops didn't work
</code></pre>
<p><em>Note: the <code>console.assert()</code> method is implemented differently in Node.js
than the <code>console.assert()</code> method <a href="https://developer.mozilla.org/en-US/docs/Web/API/console/assert">available in browsers</a>.</em></p>
<p>Specifically, in browsers, calling <code>console.assert()</code> with a falsy
assertion will cause the <code>message</code> to be printed to the console without
interrupting execution of subsequent code. In Node.js, however, a falsy
assertion will cause an <code>AssertionError</code> to be thrown.</p>
<p>Functionality approximating that implemented by browsers can be implemented
by extending Node.js' <code>console</code> and overriding the <code>console.assert()</code> method.</p>
<p>In the following example, a simple module is created that extends and overrides
the default behavior of <code>console</code> in Node.js.</p>
<pre><code class="lang-js">'use strict';
// Creates a simple extension of console with a
// new impl for assert without monkey-patching.
const myConsole = Object.create(console, {
assert: {
value: function assert(assertion, message, ...args) {
try {
console.assert(assertion, message, ...args);
} catch (err) {
console.error(err.stack);
}
},
configurable: true,
enumerable: true,
writable: true,
},
});
module.exports = myConsole;
</code></pre>
<p>This can then be used as a direct replacement for the built in console:</p>
<pre><code class="lang-js">const console = require('./myConsole');
console.assert(false, 'this message will print, but no error thrown');
console.log('this will also print');
</code></pre>
<h3>console.dir(obj[, options])<span><a class="mark" href="#console_console_dir_obj_options" id="console_console_dir_obj_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.101</span>
</div><p>Uses <a href="util.html#util_util_inspect_object_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>. An
optional <code>options</code> object may be passed to alter certain aspects of the
formatted string:</p>
<ul>
<li><p><code>showHidden</code> - if <code>true</code> then the object's non-enumerable and symbol
properties will be shown too. Defaults to <code>false</code>.</p>
</li>
<li><p><code>depth</code> - tells <a href="util.html#util_util_inspect_object_options"><code>util.inspect()</code></a> how many times to recurse while
formatting the object. This is useful for inspecting large complicated objects.
Defaults to <code>2</code>. To make it recurse indefinitely, pass <code>null</code>.</p>
</li>
<li><p><code>colors</code> - if <code>true</code>, then the output will be styled with ANSI color codes.
Defaults to <code>false</code>. Colors are customizable; see
<a href="util.html#util_customizing_util_inspect_colors">customizing <code>util.inspect()</code> colors</a>.</p>
</li>
</ul>
<h3>console.error([data][, ...])<span><a class="mark" href="#console_console_error_data" id="console_console_error_data">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.100</span>
</div><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">printf(3)</a> (the arguments are all passed to
<a href="util.html#util_util_format_format"><code>util.format()</code></a>).</p>
<pre><code class="lang-js">const code = 5;
console.error('error #%d', code);
// Prints: error #5, to stderr
console.error('error', code);
// Prints: error 5, to stderr
</code></pre>
<p>If formatting elements (e.g. <code>%d</code>) are not found in the first string then
<a href="util.html#util_util_inspect_object_options"><code>util.inspect()</code></a> is called on each argument and the resulting string
values are concatenated. See <a href="util.html#util_util_format_format"><code>util.format()</code></a> for more information.</p>
<h3>console.info([data][, ...])<span><a class="mark" href="#console_console_info_data" id="console_console_info_data">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.100</span>
</div><p>The <code>console.info()</code> function is an alias for <a href="console.html#console_console_log_data"><code>console.log()</code></a>.</p>
<h3>console.log([data][, ...])<span><a class="mark" href="#console_console_log_data" id="console_console_log_data">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.100</span>
</div><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">printf(3)</a> (the arguments are all passed to
<a href="util.html#util_util_format_format"><code>util.format()</code></a>).</p>
<pre><code class="lang-js">const count = 5;
console.log('count: %d', count);
// Prints: count: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
</code></pre>
<p>If formatting elements (e.g. <code>%d</code>) are not found in the first string then
<a href="util.html#util_util_inspect_object_options"><code>util.inspect()</code></a> is called on each argument and the resulting string
values are concatenated. See <a href="util.html#util_util_format_format"><code>util.format()</code></a> for more information.</p>
<h3>console.time(label)<span><a class="mark" href="#console_console_time_label" id="console_console_time_label">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.104</span>
</div><p>Used to calculate the duration of a specific operation. To start a timer, call
the <code>console.time()</code> method, giving it a unique <code>label</code> as the only parameter. To stop the
timer, and to get the elapsed time in milliseconds, just call the
<a href="#console_console_timeend_label"><code>console.timeEnd()</code></a> method, again passing the
timer's unique <code>label</code> as the parameter.</p>
<h3>console.timeEnd(label)<span><a class="mark" href="#console_console_timeend_label" id="console_console_timeend_label">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.104</span>
</div><p>Stops a timer that was previously started by calling <a href="#console_console_time_label"><code>console.time()</code></a> and
prints the result to stdout:</p>
<pre><code class="lang-js">console.time('100-elements');
for (let i = 0; i < 100; i++) {
;
}
console.timeEnd('100-elements');
// prints 100-elements: 262ms
</code></pre>
<h3>console.trace(message[, ...])<span><a class="mark" href="#console_console_trace_message" id="console_console_trace_message">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.104</span>
</div><p>Prints to <code>stderr</code> the string <code>'Trace :'</code>, followed by the <a href="util.html#util_util_format_format"><code>util.format()</code></a>
formatted message and stack trace to the current position in the code.</p>
<pre><code class="lang-js">console.trace('Show me');
// Prints: (stack trace will vary based on where trace is called)
// Trace: Show me
// at repl:2:9
// at REPLServer.defaultEval (repl.js:248:27)
// at bound (domain.js:287:14)
// at REPLServer.runBound [as eval] (domain.js:300:12)
// at REPLServer.<anonymous> (repl.js:412:12)
// at emitOne (events.js:82:20)
// at REPLServer.emit (events.js:169:7)
// at REPLServer.Interface._onLine (readline.js:210:10)
// at REPLServer.Interface._line (readline.js:549:8)
// at REPLServer.Interface._ttyWrite (readline.js:826:14)
</code></pre>
<h3>console.warn([data][, ...])<span><a class="mark" href="#console_console_warn_data" id="console_console_warn_data">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.100</span>
</div><p>The <code>console.warn()</code> function is an alias for <a href="console.html#console_console_error_data"><code>console.error()</code></a>.</p>
<!-- [end-include:console.md] -->
<!-- [start-include:crypto.md] -->
<h1>Crypto<span><a class="mark" href="#crypto_crypto" id="crypto_crypto">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>The <code>crypto</code> module provides cryptographic functionality that includes a set of
wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign and verify functions.</p>
<p>Use <code>require('crypto')</code> to access this module.</p>
<pre><code class="lang-js">const crypto = require('crypto');
const secret = 'abcdefg';
const hash = crypto.createHmac('sha256', secret)
.update('I love cupcakes')
.digest('hex');
console.log(hash);
// Prints:
// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
</code></pre>
<h2>Class: Certificate<span><a class="mark" href="#crypto_class_certificate" id="crypto_class_certificate">#</a></span></h2>
<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 now specified formally as part of <a href="http://www.w3.org/TR/html5/forms.html#the-keygen-element">HTML5's <code>keygen</code> element</a>.</p>
<p>The <code>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/apps/spkac.html">OpenSSL's SPKAC implementation</a> internally.</p>
<h3>new crypto.Certificate()<span><a class="mark" href="#crypto_new_crypto_certificate" id="crypto_new_crypto_certificate">#</a></span></h3>
<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><code class="lang-js">const crypto = require('crypto');
const cert1 = new crypto.Certificate();
const cert2 = crypto.Certificate();
</code></pre>
<h3>certificate.exportChallenge(spkac)<span><a class="mark" href="#crypto_certificate_exportchallenge_spkac" id="crypto_certificate_exportchallenge_spkac">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.8</span>
</div><p>The <code>spkac</code> data structure includes a public key and a challenge. The
<code>certificate.exportChallenge()</code> returns the challenge component in the
form of a Node.js <a href="buffer.html#buffer_buffer"><code>Buffer</code></a>. The <code>spkac</code> argument can be either a string
or a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a>.</p>
<pre><code class="lang-js">const cert = require('crypto').Certificate();
const spkac = getSpkacSomehow();
const challenge = cert.exportChallenge(spkac);
console.log(challenge.toString('utf8'));
// Prints the challenge as a UTF8 string
</code></pre>
<h3>certificate.exportPublicKey(spkac)<span><a class="mark" href="#crypto_certificate_exportpublickey_spkac" id="crypto_certificate_exportpublickey_spkac">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.8</span>
</div><p>The <code>spkac</code> data structure includes a public key and a challenge. The
<code>certificate.exportPublicKey()</code> returns the public key component in the
form of a Node.js <a href="buffer.html#buffer_buffer"><code>Buffer</code></a>. The <code>spkac</code> argument can be either a string
or a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a>.</p>
<pre><code class="lang-js">const cert = require('crypto').Certificate();
const spkac = getSpkacSomehow();
const publicKey = cert.exportPublicKey(spkac);
console.log(publicKey);
// Prints the public key as <Buffer ...>
</code></pre>
<h3>certificate.verifySpkac(spkac)<span><a class="mark" href="#crypto_certificate_verifyspkac_spkac" id="crypto_certificate_verifyspkac_spkac">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.8</span>
</div><p>Returns <code>true</code> if the given <code>spkac</code> data structure is valid, <code>false</code> otherwise.
The <code>spkac</code> argument must be a Node.js <a href="buffer.html#buffer_buffer"><code>Buffer</code></a>.</p>
<pre><code class="lang-js">const cert = require('crypto').Certificate();
const spkac = getSpkacSomehow();
console.log(cert.verifySpkac(new Buffer(spkac)));
// Prints true or false
</code></pre>
<h2>Class: Cipher<span><a class="mark" href="#crypto_class_cipher" id="crypto_class_cipher">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div><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_stream">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="#crypto_cipher_update_data_input_encoding_output_encoding"><code>cipher.update()</code></a> and <a href="#crypto_cipher_final_output_encoding"><code>cipher.final()</code></a> methods to produce
the encrypted data.</li>
</ul>
<p>The <a href="#crypto_crypto_createcipher_algorithm_password"><code>crypto.createCipher()</code></a> or <a href="#crypto_crypto_createcipheriv_algorithm_key_iv"><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><code class="lang-js">const crypto = require('crypto');
const cipher = crypto.createCipher('aes192', 'a password');
var encrypted = '';
cipher.on('readable', () => {
var data = cipher.read();
if (data)
encrypted += data.toString('hex');
});
cipher.on('end', () => {
console.log(encrypted);
// Prints: ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504
});
cipher.write('some clear text data');
cipher.end();
</code></pre>
<p>Example: Using <code>Cipher</code> and piped streams:</p>
<pre><code class="lang-js">const crypto = require('crypto');
const fs = require('fs');
const cipher = crypto.createCipher('aes192', 'a password');
const input = fs.createReadStream('test.js');
const output = fs.createWriteStream('test.enc');
input.pipe(cipher).pipe(output);
</code></pre>
<p>Example: Using the <a href="#crypto_cipher_update_data_input_encoding_output_encoding"><code>cipher.update()</code></a> and <a href="#crypto_cipher_final_output_encoding"><code>cipher.final()</code></a> methods:</p>
<pre><code class="lang-js">const crypto = require('crypto');
const cipher = crypto.createCipher('aes192', 'a password');
var encrypted = cipher.update('some clear text data', 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log(encrypted);
// Prints: ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504
</code></pre>
<h3>cipher.final([output_encoding])<span><a class="mark" href="#crypto_cipher_final_output_encoding" id="crypto_cipher_final_output_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div><p>Returns any remaining enciphered contents. If <code>output_encoding</code>
parameter is one of <code>'binary'</code>, <code>'base64'</code> or <code>'hex'</code>, a string is returned.
If an <code>output_encoding</code> is not provided, a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a> is returned.</p>
<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>
<h3>cipher.setAAD(buffer)<span><a class="mark" href="#crypto_cipher_setaad_buffer" id="crypto_cipher_setaad_buffer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.0.0</span>
</div><p>When using an authenticated encryption mode (only <code>GCM</code> is currently
supported), the <code>cipher.setAAD()</code> method sets the value used for the
<em>additional authenticated data</em> (AAD) input parameter.</p>
<h3>cipher.getAuthTag()<span><a class="mark" href="#crypto_cipher_getauthtag" id="crypto_cipher_getauthtag">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.0.0</span>
</div><p>When using an authenticated encryption mode (only <code>GCM</code> is currently
supported), the <code>cipher.getAuthTag()</code> method returns a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a> containing
the <em>authentication tag</em> that has been computed from the given data.</p>
<p>The <code>cipher.getAuthTag()</code> method should only be called after encryption has
been completed using the <a href="#crypto_cipher_final_output_encoding"><code>cipher.final()</code></a> method.</p>
<h3>cipher.setAutoPadding(auto_padding=true)<span><a class="mark" href="#crypto_cipher_setautopadding_auto_padding_true" id="crypto_cipher_setautopadding_auto_padding_true">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.1</span>
</div><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>auto_padding</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="#crypto_cipher_final_output_encoding"><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="#crypto_cipher_final_output_encoding"><code>cipher.final()</code></a>.</p>
<h3>cipher.update(data[, input_encoding][, output_encoding])<span><a class="mark" href="#crypto_cipher_update_data_input_encoding_output_encoding" id="crypto_cipher_update_data_input_encoding_output_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div><p>Updates the cipher with <code>data</code>. If the <code>input_encoding</code> argument is given,
it's value must be one of <code>'utf8'</code>, <code>'ascii'</code>, or <code>'binary'</code> and the <code>data</code>
argument is a string using the specified encoding. If the <code>input_encoding</code>
argument is not given, <code>data</code> must be a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a>. If <code>data</code> is a
<a href="buffer.html#buffer_buffer"><code>Buffer</code></a> then <code>input_encoding</code> is ignored.</p>
<p>The <code>output_encoding</code> specifies the output format of the enciphered
data, and can be <code>'binary'</code>, <code>'base64'</code> or <code>'hex'</code>. If the <code>output_encoding</code>
is specified, a string using the specified encoding is returned. If no
<code>output_encoding</code> is provided, a <a href="buffer.html#buffer_buffer"><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="#crypto_cipher_final_output_encoding"><code>cipher.final()</code></a> is called. Calling <code>cipher.update()</code> after
<a href="#crypto_cipher_final_output_encoding"><code>cipher.final()</code></a> will result in an error being thrown.</p>
<h2>Class: Decipher<span><a class="mark" href="#crypto_class_decipher" id="crypto_class_decipher">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div><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_stream">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="#crypto_decipher_update_data_input_encoding_output_encoding"><code>decipher.update()</code></a> and <a href="#crypto_decipher_final_output_encoding"><code>decipher.final()</code></a> methods to
produce the unencrypted data.</li>
</ul>
<p>The <a href="#crypto_crypto_createdecipher_algorithm_password"><code>crypto.createDecipher()</code></a> or <a href="#crypto_crypto_createdecipheriv_algorithm_key_iv"><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><code class="lang-js">const crypto = require('crypto');
const decipher = crypto.createDecipher('aes192', 'a password');
var decrypted = '';
decipher.on('readable', () => {
var data = decipher.read();
if (data)
decrypted += data.toString('utf8');
});
decipher.on('end', () => {
console.log(decrypted);
// Prints: some clear text data
});
var encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';
decipher.write(encrypted, 'hex');
decipher.end();
</code></pre>
<p>Example: Using <code>Decipher</code> and piped streams:</p>
<pre><code class="lang-js">const crypto = require('crypto');
const fs = require('fs');
const decipher = crypto.createDecipher('aes192', 'a password');
const input = fs.createReadStream('test.enc');
const output = fs.createWriteStream('test.js');
input.pipe(decipher).pipe(output);
</code></pre>
<p>Example: Using the <a href="#crypto_decipher_update_data_input_encoding_output_encoding"><code>decipher.update()</code></a> and <a href="#crypto_decipher_final_output_encoding"><code>decipher.final()</code></a> methods:</p>
<pre><code class="lang-js">const crypto = require('crypto');
const decipher = crypto.createDecipher('aes192', 'a password');
var encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';
var decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted);
// Prints: some clear text data
</code></pre>
<h3>decipher.final([output_encoding])<span><a class="mark" href="#crypto_decipher_final_output_encoding" id="crypto_decipher_final_output_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div><p>Returns any remaining deciphered contents. If <code>output_encoding</code>
parameter is one of <code>'binary'</code>, <code>'base64'</code> or <code>'hex'</code>, a string is returned.
If an <code>output_encoding</code> is not provided, a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a> is returned.</p>
<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>
<h3>decipher.setAAD(buffer)<span><a class="mark" href="#crypto_decipher_setaad_buffer" id="crypto_decipher_setaad_buffer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.0.0</span>
</div><p>When using an authenticated encryption mode (only <code>GCM</code> is currently
supported), the <code>decipher.setAAD()</code> method sets the value used for the
<em>additional authenticated data</em> (AAD) input parameter.</p>
<h3>decipher.setAuthTag(buffer)<span><a class="mark" href="#crypto_decipher_setauthtag_buffer" id="crypto_decipher_setauthtag_buffer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.0.0</span>
</div><p>When using an authenticated encryption mode (only <code>GCM</code> is 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="#crypto_decipher_final_output_encoding"><code>decipher.final()</code></a> with throw, indicating that the
cipher text should be discarded due to failed authentication.</p>
<h3>decipher.setAutoPadding(auto_padding=true)<span><a class="mark" href="#crypto_decipher_setautopadding_auto_padding_true" id="crypto_decipher_setautopadding_auto_padding_true">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.1</span>
</div><p>When data has been encrypted without standard block padding, calling
<code>decipher.setAutoPadding(false)</code> will disable automatic padding to prevent
<a href="#crypto_decipher_final_output_encoding"><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="#crypto_decipher_update_data_input_encoding_output_encoding"><code>decipher.update()</code></a>.</p>
<h3>decipher.update(data[, input_encoding][, output_encoding])<span><a class="mark" href="#crypto_decipher_update_data_input_encoding_output_encoding" id="crypto_decipher_update_data_input_encoding_output_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div><p>Updates the decipher with <code>data</code>. If the <code>input_encoding</code> argument is given,
it's value must be one of <code>'binary'</code>, <code>'base64'</code>, or <code>'hex'</code> and the <code>data</code>
argument is a string using the specified encoding. If the <code>input_encoding</code>
argument is not given, <code>data</code> must be a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a>. If <code>data</code> is a
<a href="buffer.html#buffer_buffer"><code>Buffer</code></a> then <code>input_encoding</code> is ignored.</p>
<p>The <code>output_encoding</code> specifies the output format of the enciphered
data, and can be <code>'binary'</code>, <code>'ascii'</code> or <code>'utf8'</code>. If the <code>output_encoding</code>
is specified, a string using the specified encoding is returned. If no
<code>output_encoding</code> is provided, a <a href="buffer.html#buffer_buffer"><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="#crypto_decipher_final_output_encoding"><code>decipher.final()</code></a> is called. Calling <code>decipher.update()</code> after
<a href="#crypto_decipher_final_output_encoding"><code>decipher.final()</code></a> will result in an error being thrown.</p>
<h2>Class: DiffieHellman<span><a class="mark" href="#crypto_class_diffiehellman" id="crypto_class_diffiehellman">#</a></span></h2>
<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="#crypto_crypto_creatediffiehellman_prime_prime_encoding_generator_generator_encoding"><code>crypto.createDiffieHellman()</code></a> function.</p>
<pre><code class="lang-js">const crypto = require('crypto');
const assert = require('assert');
// Generate Alice's keys...
const alice = crypto.createDiffieHellman(2048);
const alice_key = alice.generateKeys();
// Generate Bob's keys...
const bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator());
const bob_key = bob.generateKeys();
// Exchange and generate the secret...
const alice_secret = alice.computeSecret(bob_key);
const bob_secret = bob.computeSecret(alice_key);
// OK
assert.equal(alice_secret.toString('hex'), bob_secret.toString('hex'));
</code></pre>
<h3>diffieHellman.computeSecret(other_public_key[, input_encoding][, output_encoding])<span><a class="mark" href="#crypto_diffiehellman_computesecret_other_public_key_input_encoding_output_encoding" id="crypto_diffiehellman_computesecret_other_public_key_input_encoding_output_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div><p>Computes the shared secret using <code>other_public_key</code> as the other
party's public key and returns the computed shared secret. The supplied
key is interpreted using the specified <code>input_encoding</code>, and secret is
encoded using specified <code>output_encoding</code>. Encodings can be
<code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>. If the <code>input_encoding</code> is not
provided, <code>other_public_key</code> is expected to be a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a>.</p>
<p>If <code>output_encoding</code> is given a string is returned; otherwise, a
<a href="buffer.html#buffer_buffer"><code>Buffer</code></a> is returned.</p>
<h3>diffieHellman.generateKeys([encoding])<span><a class="mark" href="#crypto_diffiehellman_generatekeys_encoding" id="crypto_diffiehellman_generatekeys_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div><p>Generates private and public Diffie-Hellman key values, and returns
the public key in the specified <code>encoding</code>. This key should be
transferred to the other party. Encoding can be <code>'binary'</code>, <code>'hex'</code>,
or <code>'base64'</code>. If <code>encoding</code> is provided a string is returned; otherwise a
<a href="buffer.html#buffer_buffer"><code>Buffer</code></a> is returned.</p>
<h3>diffieHellman.getGenerator([encoding])<span><a class="mark" href="#crypto_diffiehellman_getgenerator_encoding" id="crypto_diffiehellman_getgenerator_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div><p>Returns the Diffie-Hellman generator in the specified <code>encoding</code>, which can
be <code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>. If <code>encoding</code> is provided a string is
returned; otherwise a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a> is returned.</p>
<h3>diffieHellman.getPrime([encoding])<span><a class="mark" href="#crypto_diffiehellman_getprime_encoding" id="crypto_diffiehellman_getprime_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div><p>Returns the Diffie-Hellman prime in the specified <code>encoding</code>, which can
be <code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>. If <code>encoding</code> is provided a string is
returned; otherwise a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a> is returned.</p>
<h3>diffieHellman.getPrivateKey([encoding])<span><a class="mark" href="#crypto_diffiehellman_getprivatekey_encoding" id="crypto_diffiehellman_getprivatekey_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div><p>Returns the Diffie-Hellman private key in the specified <code>encoding</code>,
which can be <code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>. If <code>encoding</code> is provided a
string is returned; otherwise a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a> is returned.</p>
<h3>diffieHellman.getPublicKey([encoding])<span><a class="mark" href="#crypto_diffiehellman_getpublickey_encoding" id="crypto_diffiehellman_getpublickey_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div><p>Returns the Diffie-Hellman public key in the specified <code>encoding</code>, which
can be <code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>. If <code>encoding</code> is provided a
string is returned; otherwise a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a> is returned.</p>
<h3>diffieHellman.setPrivateKey(private_key[, encoding])<span><a class="mark" href="#crypto_diffiehellman_setprivatekey_private_key_encoding" id="crypto_diffiehellman_setprivatekey_private_key_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div><p>Sets the Diffie-Hellman private key. If the <code>encoding</code> argument is provided
and is either <code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>, <code>private_key</code> is expected
to be a string. If no <code>encoding</code> is provided, <code>private_key</code> is expected
to be a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a>.</p>
<h3>diffieHellman.setPublicKey(public_key[, encoding])<span><a class="mark" href="#crypto_diffiehellman_setpublickey_public_key_encoding" id="crypto_diffiehellman_setpublickey_public_key_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div><p>Sets the Diffie-Hellman public key. If the <code>encoding</code> argument is provided
and is either <code>'binary'</code>, <code>'hex'</code> or <code>'base64'</code>, <code>public_key</code> is expected
to be a string. If no <code>encoding</code> is provided, <code>public_key</code> is expected
to be a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a>.</p>
<h3>diffieHellman.verifyError<span><a class="mark" href="#crypto_diffiehellman_verifyerror" id="crypto_diffiehellman_verifyerror">#</a></span></h3>
<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>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>
<h2>Class: ECDH<span><a class="mark" href="#crypto_class_ecdh" id="crypto_class_ecdh">#</a></span></h2>
<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="#crypto_crypto_createecdh_curve_name"><code>crypto.createECDH()</code></a> function.</p>
<pre><code class="lang-js">const crypto = require('crypto');
const assert = require('assert');
// Generate Alice's keys...
const alice = crypto.createECDH('secp521r1');
const alice_key = alice.generateKeys();
// Generate Bob's keys...
const bob = crypto.createECDH('secp521r1');
const bob_key = bob.generateKeys();
// Exchange and generate the secret...
const alice_secret = alice.computeSecret(bob_key);
const bob_secret = bob.computeSecret(alice_key);
assert(alice_secret, bob_secret);
// OK
</code></pre>
<h3>ecdh.computeSecret(other_public_key[, input_encoding][, output_encoding])<span><a class="mark" href="#crypto_ecdh_computesecret_other_public_key_input_encoding_output_encoding" id="crypto_ecdh_computesecret_other_public_key_input_encoding_output_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div><p>Computes the shared secret using <code>other_public_key</code> as the other
party's public key and returns the computed shared secret. The supplied
key is interpreted using specified <code>input_encoding</code>, and the returned secret
is encoded using the specified <code>output_encoding</code>. Encodings can be
<code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>. If the <code>input_encoding</code> is not
provided, <code>other_public_key</code> is expected to be a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a>.</p>
<p>If <code>output_encoding</code> is given a string will be returned; otherwise a
<a href="buffer.html#buffer_buffer"><code>Buffer</code></a> is returned.</p>
<h3>ecdh.generateKeys([encoding[, format]])<span><a class="mark" href="#crypto_ecdh_generatekeys_encoding_format" id="crypto_ecdh_generatekeys_encoding_format">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div><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> arguments specifies point encoding and can be <code>'compressed'</code>,
<code>'uncompressed'</code>, or <code>'hybrid'</code>. If <code>format</code> is not specified, the point will
be returned in <code>'uncompressed'</code> format.</p>
<p>The <code>encoding</code> argument can be <code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>. If
<code>encoding</code> is provided a string is returned; otherwise a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a>
is returned.</p>
<h3>ecdh.getPrivateKey([encoding])<span><a class="mark" href="#crypto_ecdh_getprivatekey_encoding" id="crypto_ecdh_getprivatekey_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div><p>Returns the EC Diffie-Hellman private key in the specified <code>encoding</code>,
which can be <code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>. If <code>encoding</code> is provided
a string is returned; otherwise a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a> is returned.</p>
<h3>ecdh.getPublicKey([encoding[, format]])<span><a class="mark" href="#crypto_ecdh_getpublickey_encoding_format" id="crypto_ecdh_getpublickey_encoding_format">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div><p>Returns the EC Diffie-Hellman public key in the specified <code>encoding</code> and
<code>format</code>.</p>
<p>The <code>format</code> argument specifies point encoding and can be <code>'compressed'</code>,
<code>'uncompressed'</code>, or <code>'hybrid'</code>. If <code>format</code> is not specified the point will be
returned in <code>'uncompressed'</code> format.</p>
<p>The <code>encoding</code> argument can be <code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>. If
<code>encoding</code> is specified, a string is returned; otherwise a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a> is
returned.</p>
<h3>ecdh.setPrivateKey(private_key[, encoding])<span><a class="mark" href="#crypto_ecdh_setprivatekey_private_key_encoding" id="crypto_ecdh_setprivatekey_private_key_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div><p>Sets the EC Diffie-Hellman private key. The <code>encoding</code> can be <code>'binary'</code>,
<code>'hex'</code> or <code>'base64'</code>. If <code>encoding</code> is provided, <code>private_key</code> is expected
to be a string; otherwise <code>private_key</code> is expected to be a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a>. If
<code>private_key</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 ECDH object.</p>
<h3>ecdh.setPublicKey(public_key[, encoding])<span><a class="mark" href="#crypto_ecdh_setpublickey_public_key_encoding" id="crypto_ecdh_setpublickey_public_key_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
<span>Deprecated since: v5.2.0 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated</pre><p>Sets the EC Diffie-Hellman public key. Key encoding can be <code>'binary'</code>,
<code>'hex'</code> or <code>'base64'</code>. If <code>encoding</code> is provided <code>public_key</code> is expected to
be a string; otherwise a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a> is expected.</p>
<p>Note that 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="#crypto_ecdh_generatekeys_encoding_format"><code>ecdh.generateKeys()</code></a> or
<a href="#crypto_ecdh_setprivatekey_private_key_encoding"><code>ecdh.setPrivateKey()</code></a> will be called. The <a href="#crypto_ecdh_setprivatekey_private_key_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><code class="lang-js">const crypto = require('crypto');
const alice = crypto.createECDH('secp256k1');
const bob = crypto.createECDH('secp256k1');
// Note: This is a shortcut way to specify one of Alice's previous private
// keys. It would be unwise to use such a predictable private key in a real
// application.
alice.setPrivateKey(
crypto.createHash('sha256').update('alice', 'utf8').digest()
);
// Bob uses a newly generated cryptographically strong
// pseudorandom key pair bob.generateKeys();
const alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
// alice_secret and bob_secret should be the same shared secret value
console.log(alice_secret === bob_secret);
</code></pre>
<h2>Class: Hash<span><a class="mark" href="#crypto_class_hash" id="crypto_class_hash">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
</div><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_stream">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="#crypto_hash_update_data_input_encoding"><code>hash.update()</code></a> and <a href="#crypto_hash_digest_encoding"><code>hash.digest()</code></a> methods to produce the
computed hash.</li>
</ul>
<p>The <a href="#crypto_crypto_createhash_algorithm"><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><code class="lang-js">const crypto = require('crypto');
const hash = crypto.createHash('sha256');
hash.on('readable', () => {
var data = hash.read();
if (data)
console.log(data.toString('hex'));
// Prints:
// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
});
hash.write('some data to hash');
hash.end();
</code></pre>
<p>Example: Using <code>Hash</code> and piped streams:</p>
<pre><code class="lang-js">const crypto = require('crypto');
const fs = require('fs');
const hash = crypto.createHash('sha256');
const input = fs.createReadStream('test.js');
input.pipe(hash).pipe(process.stdout);
</code></pre>
<p>Example: Using the <a href="#crypto_hash_update_data_input_encoding"><code>hash.update()</code></a> and <a href="#crypto_hash_digest_encoding"><code>hash.digest()</code></a> methods:</p>
<pre><code class="lang-js">const crypto = require('crypto');
const hash = crypto.createHash('sha256');
hash.update('some data to hash');
console.log(hash.digest('hex'));
// Prints:
// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
</code></pre>
<h3>hash.digest([encoding])<span><a class="mark" href="#crypto_hash_digest_encoding" id="crypto_hash_digest_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
</div><p>Calculates the digest of all of the data passed to be hashed (using the
<a href="#crypto_hash_update_data_input_encoding"><code>hash.update()</code></a> method). The <code>encoding</code> can be <code>'hex'</code>, <code>'binary'</code> or
<code>'base64'</code>. If <code>encoding</code> is provided a string will be returned; otherwise
a <a href="buffer.html#buffer_buffer"><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>
<h3>hash.update(data[, input_encoding])<span><a class="mark" href="#crypto_hash_update_data_input_encoding" id="crypto_hash_update_data_input_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
</div><p>Updates the hash content with the given <code>data</code>, the encoding of which
is given in <code>input_encoding</code> and can be <code>'utf8'</code>, <code>'ascii'</code> or
<code>'binary'</code>. If <code>encoding</code> is not provided, and the <code>data</code> is a string, an
encoding of <code>'binary'</code> is enforced. If <code>data</code> is a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a> then
<code>input_encoding</code> is ignored.</p>
<p>This can be called many times with new data as it is streamed.</p>
<h2>Class: Hmac<span><a class="mark" href="#crypto_class_hmac" id="crypto_class_hmac">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div><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_stream">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="#crypto_hmac_update_data"><code>hmac.update()</code></a> and <a href="#crypto_hmac_digest_encoding"><code>hmac.digest()</code></a> methods to produce the
computed HMAC digest.</li>
</ul>
<p>The <a href="#crypto_crypto_createhmac_algorithm_key"><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><code class="lang-js">const crypto = require('crypto');
const hmac = crypto.createHmac('sha256', 'a secret');
hmac.on('readable', () => {
var data = hmac.read();
if (data)
console.log(data.toString('hex'));
// Prints:
// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
});
hmac.write('some data to hash');
hmac.end();
</code></pre>
<p>Example: Using <code>Hmac</code> and piped streams:</p>
<pre><code class="lang-js">const crypto = require('crypto');
const fs = require('fs');
const hmac = crypto.createHmac('sha256', 'a secret');
const input = fs.createReadStream('test.js');
input.pipe(hmac).pipe(process.stdout);
</code></pre>
<p>Example: Using the <a href="#crypto_hmac_update_data"><code>hmac.update()</code></a> and <a href="#crypto_hmac_digest_encoding"><code>hmac.digest()</code></a> methods:</p>
<pre><code class="lang-js">const crypto = require('crypto');
const hmac = crypto.createHmac('sha256', 'a secret');
hmac.update('some data to hash');
console.log(hmac.digest('hex'));
// Prints:
// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
</code></pre>
<h3>hmac.digest([encoding])<span><a class="mark" href="#crypto_hmac_digest_encoding" id="crypto_hmac_digest_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div><p>Calculates the HMAC digest of all of the data passed using <a href="#crypto_hmac_update_data"><code>hmac.update()</code></a>.
The <code>encoding</code> can be <code>'hex'</code>, <code>'binary'</code> or <code>'base64'</code>. If <code>encoding</code> is
provided a string is returned; otherwise a <a href="buffer.html#buffer_buffer"><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>
<h3>hmac.update(data[, input_encoding])<span><a class="mark" href="#crypto_hmac_update_data_input_encoding" id="crypto_hmac_update_data_input_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div><p>Updates the <code>Hmac</code> content with the given <code>data</code>, the encoding of which
is given in <code>input_encoding</code> and can be <code>'utf8'</code>, <code>'ascii'</code> or
<code>'binary'</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#buffer_buffer"><code>Buffer</code></a> then
<code>input_encoding</code> is ignored.</p>
<p>This can be called many times with new data as it is streamed.</p>
<h2>Class: Sign<span><a class="mark" href="#crypto_class_sign" id="crypto_class_sign">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
</div><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_stream">stream</a>, where data to be signed is written and the
<a href="#crypto_sign_sign_private_key_output_format"><code>sign.sign()</code></a> method is used to generate and return the signature, or</li>
<li>Using the <a href="#crypto_sign_update_data"><code>sign.update()</code></a> and <a href="#crypto_sign_sign_private_key_output_format"><code>sign.sign()</code></a> methods to produce the
signature.</li>
</ul>
<p>The <a href="#crypto_crypto_createsign_algorithm"><code>crypto.createSign()</code></a> method is used to create <code>Sign</code> instances. <code>Sign</code>
objects are not to be created directly using the <code>new</code> keyword.</p>
<p>Example: Using <code>Sign</code> objects as streams:</p>
<pre><code class="lang-js">const crypto = require('crypto');
const sign = crypto.createSign('RSA-SHA256');
sign.write('some data to sign');
sign.end();
const private_key = getPrivateKeySomehow();
console.log(sign.sign(private_key, 'hex'));
// Prints the calculated signature
</code></pre>
<p>Example: Using the <a href="#crypto_sign_update_data"><code>sign.update()</code></a> and <a href="#crypto_sign_sign_private_key_output_format"><code>sign.sign()</code></a> methods:</p>
<pre><code class="lang-js">const crypto = require('crypto');
const sign = crypto.createSign('RSA-SHA256');
sign.update('some data to sign');
const private_key = getPrivateKeySomehow();
console.log(sign.sign(private_key, 'hex'));
// Prints the calculated signature
</code></pre>
<p>A <code>Sign</code> instance can also be created by just passing in the digest
algorithm name, in which case OpenSSL will infer the full signature algorithm
from the type of the PEM-formatted private key, including algorithms that
do not have directly exposed name constants, e.g. 'ecdsa-with-SHA256'.</p>
<p>Example: signing using ECDSA with SHA256</p>
<pre><code class="lang-js">const crypto = require('crypto');
const sign = crypto.createSign('sha256');
sign.update('some data to sign');
const private_key = '-----BEGIN EC PRIVATE KEY-----\n' +
'MHcCAQEEIF+jnWY1D5kbVYDNvxxo/Y+ku2uJPDwS0r/VuPZQrjjVoAoGCCqGSM49\n' +
'AwEHoUQDQgAEurOxfSxmqIRYzJVagdZfMMSjRNNhB8i3mXyIMq704m2m52FdfKZ2\n' +
'pQhByd5eyj3lgZ7m7jbchtdgyOF8Io/1ng==\n' +
'-----END EC PRIVATE KEY-----\n';
console.log(sign.sign(private_key).toString('hex'));
</code></pre>
<h3>sign.sign(private_key[, output_format])<span><a class="mark" href="#crypto_sign_sign_private_key_output_format" id="crypto_sign_sign_private_key_output_format">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
</div><p>Calculates the signature on all the data passed through using either
<a href="#crypto_sign_update_data"><code>sign.update()</code></a> or <a href="stream.html#stream_writable_write_chunk_encoding_callback"><code>sign.write()</code></a>.</p>
<p>The <code>private_key</code> argument can be an object or a string. If <code>private_key</code> is a
string, it is treated as a raw key with no passphrase. If <code>private_key</code> is an
object, it is interpreted as a hash containing two properties:</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> - 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> - passphrase for the private key</li>
</ul>
<p>The <code>output_format</code> can specify one of <code>'binary'</code>, <code>'hex'</code> or <code>'base64'</code>. If
<code>output_format</code> is provided a string is returned; otherwise a <a href="buffer.html#buffer_buffer"><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>
<h3>sign.update(data[, input_encoding])<span><a class="mark" href="#crypto_sign_update_data_input_encoding" id="crypto_sign_update_data_input_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
</div><p>Updates the <code>Sign</code> content with the given <code>data</code>, the encoding of which
is given in <code>input_encoding</code> and can be <code>'utf8'</code>, <code>'ascii'</code> or
<code>'binary'</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#buffer_buffer"><code>Buffer</code></a> then
<code>input_encoding</code> is ignored.</p>
<p>This can be called many times with new data as it is streamed.</p>
<h2>Class: Verify<span><a class="mark" href="#crypto_class_verify" id="crypto_class_verify">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
</div><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_stream">stream</a> where written data is used to validate against the
supplied signature, or</li>
<li>Using the <a href="#crypto_verifier_update_data"><code>verify.update()</code></a> and <a href="#crypto_verifier_verify_object_signature_signature_format"><code>verify.verify()</code></a> methods to verify
the signature.</li>
</ul>
<p>The [<code>crypto.createVerify()</code>][] 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>Example: Using <code>Verify</code> objects as streams:</p>
<pre><code class="lang-js">const crypto = require('crypto');
const verify = crypto.createVerify('RSA-SHA256');
verify.write('some data to sign');
verify.end();
const public_key = getPublicKeySomehow();
const signature = getSignatureToVerify();
console.log(verify.verify(public_key, signature));
// Prints true or false
</code></pre>
<p>Example: Using the <a href="#crypto_verifier_update_data"><code>verify.update()</code></a> and <a href="#crypto_verifier_verify_object_signature_signature_format"><code>verify.verify()</code></a> methods:</p>
<pre><code class="lang-js">const crypto = require('crypto');
const verify = crypto.createVerify('RSA-SHA256');
verify.update('some data to sign');
const public_key = getPublicKeySomehow();
const signature = getSignatureToVerify();
console.log(verify.verify(public_key, signature));
// Prints true or false
</code></pre>
<h3>verifier.update(data[, input_encoding])<span><a class="mark" href="#crypto_verifier_update_data_input_encoding" id="crypto_verifier_update_data_input_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
</div><p>Updates the <code>Verify</code> content with the given <code>data</code>, the encoding of which
is given in <code>input_encoding</code> and can be <code>'utf8'</code>, <code>'ascii'</code> or
<code>'binary'</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#buffer_buffer"><code>Buffer</code></a> then
<code>input_encoding</code> is ignored.</p>
<p>This can be called many times with new data as it is streamed.</p>
<h3>verifier.verify(object, signature[, signature_format])<span><a class="mark" href="#crypto_verifier_verify_object_signature_signature_format" id="crypto_verifier_verify_object_signature_signature_format">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
</div><p>Verifies the provided data using the given <code>object</code> and <code>signature</code>.
The <code>object</code> argument is a string containing a PEM encoded object, which can be
one an RSA public key, a DSA public key, or an X.509 certificate.
The <code>signature</code> argument is the previously calculated signature for the data, in
the <code>signature_format</code> which can be <code>'binary'</code>, <code>'hex'</code> or <code>'base64'</code>.
If a <code>signature_format</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#buffer_buffer"><code>Buffer</code></a>.</p>
<p>Returns <code>true</code> or <code>false</code> depending on the validity of the signature for
the data and public key.</p>
<p>The <code>verifier</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>
<h2><code>crypto</code> module methods and properties<span><a class="mark" href="#crypto_crypto_module_methods_and_properties" id="crypto_crypto_module_methods_and_properties">#</a></span></h2>
<h3>crypto.DEFAULT_ENCODING<span><a class="mark" href="#crypto_crypto_default_encoding" id="crypto_crypto_default_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.3</span>
</div><p>The default encoding to use for functions that can take either strings
or <a href="buffer.html#buffer_buffer">buffers</a>. The default value is <code>'buffer'</code>, which makes methods
default to <a href="buffer.html#buffer_buffer"><code>Buffer</code></a> objects.</p>
<p>The <code>crypto.DEFAULT_ENCODING</code> mechanism is provided for backwards compatibility
with legacy programs that expect <code>'binary'</code> to be the default encoding.</p>
<p>New applications should expect the default to be <code>'buffer'</code>. This property may
become deprecated in a future Node.js release.</p>
<h3>crypto.createCipher(algorithm, password)<span><a class="mark" href="#crypto_crypto_createcipher_algorithm_password" id="crypto_crypto_createcipher_algorithm_password">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div><p>Creates and returns a <code>Cipher</code> object that uses the given <code>algorithm</code> and
<code>password</code>.</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>'binary'</code> encoded string or a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a>.</p>
<p>The implementation of <code>crypto.createCipher()</code> derives keys using the OpenSSL
function <a href="https://www.openssl.org/docs/crypto/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 pbkdf2 instead of
<a href="https://www.openssl.org/docs/crypto/EVP_BytesToKey.html"><code>EVP_BytesToKey</code></a> it is recommended that developers derive a key and IV on
their own using <a href="#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback"><code>crypto.pbkdf2()</code></a> and to use <a href="#crypto_crypto_createcipheriv_algorithm_key_iv"><code>crypto.createCipheriv()</code></a>
to create the <code>Cipher</code> object.</p>
<h3>crypto.createCipheriv(algorithm, key, iv)<span><a class="mark" href="#crypto_crypto_createcipheriv_algorithm_key_iv" id="crypto_crypto_createcipheriv_algorithm_key_iv">#</a></span></h3>
<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>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>'binary'</code> encoded strings or
<a href="buffer.html#buffer_buffer">buffers</a>.</p>
<h3>crypto.createCredentials(details)<span><a class="mark" href="#crypto_crypto_createcredentials_details" id="crypto_crypto_createcredentials_details">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
<span>Deprecated since: v0.11.13 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated: Use <a href="#tls_tls_createsecurecontext_details"><code>tls.createSecureContext()</code></a> instead.</pre><p>The <code>crypto.createCredentials()</code> method is a deprecated alias for creating
and returning a <code>tls.SecureContext</code> object. The <code>crypto.createCredentials()</code>
method should not be used.</p>
<p>The optional <code>details</code> argument is a hash object with keys:</p>
<ul>
<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="buffer.html#buffer_class_buffer" class="type"><Buffer></a> - PFX or PKCS12 encoded private
key, certificate and CA certificates</li>
<li><code>key</code> : <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></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> - passphrase for the private key or PFX</li>
<li><code>cert</code> : <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> - PEM encoded certificate</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/Reference/Global_Objects/Array" class="type"><Array></a> - Either a string or array of strings of PEM encoded CA
certificates to trust.</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/Reference/Global_Objects/Array" class="type"><Array></a> - Either a string or array of strings of PEM encoded CRLs
(Certificate Revocation List)</li>
<li><code>ciphers</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> using the <a href="https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT">OpenSSL cipher list format</a> describing the
cipher algorithms to use or exclude.</li>
</ul>
<p>If no 'ca' details are given, Node.js will use Mozilla's default
<a href="https://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt">publicly trusted list of CAs</a>.</p>
<h3>crypto.createDecipher(algorithm, password)<span><a class="mark" href="#crypto_crypto_createdecipher_algorithm_password" id="crypto_crypto_createdecipher_algorithm_password">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div><p>Creates and returns a <code>Decipher</code> object that uses the given <code>algorithm</code> and
<code>password</code> (key).</p>
<p>The implementation of <code>crypto.createDecipher()</code> derives keys using the OpenSSL
function <a href="https://www.openssl.org/docs/crypto/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 pbkdf2 instead of
<a href="https://www.openssl.org/docs/crypto/EVP_BytesToKey.html"><code>EVP_BytesToKey</code></a> it is recommended that developers derive a key and IV on
their own using <a href="#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback"><code>crypto.pbkdf2()</code></a> and to use <a href="#crypto_crypto_createdecipheriv_algorithm_key_iv"><code>crypto.createDecipheriv()</code></a>
to create the <code>Decipher</code> object.</p>
<h3>crypto.createDecipheriv(algorithm, key, iv)<span><a class="mark" href="#crypto_crypto_createdecipheriv_algorithm_key_iv" id="crypto_crypto_createdecipheriv_algorithm_key_iv">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div><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>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>'binary'</code> encoded strings or
<a href="buffer.html#buffer_buffer">buffers</a>.</p>
<h3>crypto.createDiffieHellman(prime[, prime_encoding][, generator][, generator_encoding])<span><a class="mark" href="#crypto_crypto_creatediffiehellman_prime_prime_encoding_generator_generator_encoding" id="crypto_crypto_creatediffiehellman_prime_prime_encoding_generator_generator_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.12</span>
</div><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#buffer_buffer"><code>Buffer</code></a>. If
<code>generator</code> is not specified, the value <code>2</code> is used.</p>
<p>The <code>prime_encoding</code> and <code>generator_encoding</code> arguments can be <code>'binary'</code>,
<code>'hex'</code>, or <code>'base64'</code>.</p>
<p>If <code>prime_encoding</code> is specified, <code>prime</code> is expected to be a string; otherwise
a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a> is expected.</p>
<p>If <code>generator_encoding</code> is specified, <code>generator</code> is expected to be a string;
otherwise either a number or <a href="buffer.html#buffer_buffer"><code>Buffer</code></a> is expected.</p>
<h3>crypto.createDiffieHellman(prime_length[, generator])<span><a class="mark" href="#crypto_crypto_creatediffiehellman_prime_length_generator" id="crypto_crypto_creatediffiehellman_prime_length_generator">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div><p>Creates a <code>DiffieHellman</code> key exchange object and generates a prime of
<code>prime_length</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>
<h3>crypto.createECDH(curve_name)<span><a class="mark" href="#crypto_crypto_createecdh_curve_name" id="crypto_crypto_createecdh_curve_name">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div><p>Creates an Elliptic Curve Diffie-Hellman (<code>ECDH</code>) key exchange object using a
predefined curve specified by the <code>curve_name</code> string. Use
<a href="crypto.html#crypto_crypto_getcurves"><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>
<h3>crypto.createHash(algorithm)<span><a class="mark" href="#crypto_crypto_createhash_algorithm" id="crypto_crypto_createhash_algorithm">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
</div><p>Creates and returns a <code>Hash</code> object that can be used to generate hash digests
using the given <code>algorithm</code>.</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-message-digest-algorithms</code> will
display the available digest algorithms.</p>
<p>Example: generating the sha256 sum of a file</p>
<pre><code class="lang-js">const filename = process.argv[2];
const crypto = require('crypto');
const fs = require('fs');
const hash = crypto.createHash('sha256');
const input = fs.createReadStream(filename);
input.on('readable', () => {
var data = input.read();
if (data)
hash.update(data);
else {
console.log(`${hash.digest('hex')} ${filename}`);
}
});
</code></pre>
<h3>crypto.createHmac(algorithm, key)<span><a class="mark" href="#crypto_crypto_createhmac_algorithm_key" id="crypto_crypto_createhmac_algorithm_key">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div><p>Creates and returns an <code>Hmac</code> object that uses the given <code>algorithm</code> and <code>key</code>.</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-message-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.</p>
<p>Example: generating the sha256 HMAC of a file</p>
<pre><code class="lang-js">const filename = process.argv[2];
const crypto = require('crypto');
const fs = require('fs');
const hmac = crypto.createHmac('sha256', 'a secret');
const input = fs.createReadStream(filename);
input.on('readable', () => {
var data = input.read();
if (data)
hmac.update(data);
else {
console.log(`${hmac.digest('hex')} ${filename}`);
}
});
</code></pre>
<h3>crypto.createSign(algorithm)<span><a class="mark" href="#crypto_crypto_createsign_algorithm" id="crypto_crypto_createsign_algorithm">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
</div><p>Creates and returns a <code>Sign</code> object that uses the given <code>algorithm</code>.
Use <a href="#crypto_crypto_gethashes"><code>crypto.getHashes()</code></a> to obtain an array of names of the available
signing algorithms.</p>
<h3>crypto.createVerify(algorithm)<span><a class="mark" href="#crypto_crypto_createverify_algorithm" id="crypto_crypto_createverify_algorithm">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
</div><p>Creates and returns a <code>Verify</code> object that uses the given algorithm.
Use <a href="#crypto_crypto_gethashes"><code>crypto.getHashes()</code></a> to obtain an array of names of the available
signing algorithms.</p>
<h3>crypto.getCiphers()<span><a class="mark" href="#crypto_crypto_getciphers" id="crypto_crypto_getciphers">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.3</span>
</div><p>Returns an array with the names of the supported cipher algorithms.</p>
<p>Example:</p>
<pre><code class="lang-js">const ciphers = crypto.getCiphers();
console.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...]
</code></pre>
<h3>crypto.getCurves()<span><a class="mark" href="#crypto_crypto_getcurves" id="crypto_crypto_getcurves">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v2.3.0</span>
</div><p>Returns an array with the names of the supported elliptic curves.</p>
<p>Example:</p>
<pre><code class="lang-js">const curves = crypto.getCurves();
console.log(curves); // ['secp256k1', 'secp384r1', ...]
</code></pre>
<h3>crypto.getDiffieHellman(group_name)<span><a class="mark" href="#crypto_crypto_getdiffiehellman_group_name" id="crypto_crypto_getdiffiehellman_group_name">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.5</span>
</div><p>Creates a predefined <code>DiffieHellman</code> key exchange object. The
supported groups are: <code>'modp1'</code>, <code>'modp2'</code>, <code>'modp5'</code> (defined in
<a href="https://www.rfc-editor.org/rfc/rfc2412.txt">RFC 2412</a>, but see <a href="#fs_caveats">Caveats</a>) and <code>'modp14'</code>, <code>'modp15'</code>,
<code>'modp16'</code>, <code>'modp17'</code>, <code>'modp18'</code> (defined in <a href="https://www.rfc-editor.org/rfc/rfc3526.txt">RFC 3526</a>). The
returned object mimics the interface of objects created by
<a href="#crypto_crypto_creatediffiehellman_prime_prime_encoding_generator_generator_encoding"><code>crypto.createDiffieHellman()</code></a>, but will not allow changing
the keys (with <a href="#crypto_diffiehellman_setpublickey_public_key_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><code class="lang-js">const crypto = require('crypto');
const alice = crypto.getDiffieHellman('modp14');
const bob = crypto.getDiffieHellman('modp14');
alice.generateKeys();
bob.generateKeys();
const alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
/* alice_secret and bob_secret should be the same */
console.log(alice_secret == bob_secret);
</code></pre>
<h3>crypto.getHashes()<span><a class="mark" href="#crypto_crypto_gethashes" id="crypto_crypto_gethashes">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.3</span>
</div><p>Returns an array of the names of the supported hash algorithms,
such as <code>RSA-SHA256</code>.</p>
<p>Example:</p>
<pre><code class="lang-js">const hashes = crypto.getHashes();
console.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...]
</code></pre>
<h3>crypto.pbkdf2(password, salt, iterations, keylen[, digest], callback)<span><a class="mark" href="#crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback" id="crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.5</span>
</div><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>. If the <code>digest</code> algorithm is not specified,
a default of <code>'sha1'</code> is used.</p>
<p>The supplied <code>callback</code> function is called with two arguments: <code>err</code> and
<code>derivedKey</code>. If an error occurs, <code>err</code> will be set; otherwise <code>err</code> will be
null. The successfully generated <code>derivedKey</code> will be passed as a <a href="buffer.html#buffer_buffer"><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 also be as unique as possible. It is recommended that the
salts are random and their lengths are greater than 16 bytes. See
<a href="http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf">NIST SP 800-132</a> for details.</p>
<p>Example:</p>
<pre><code class="lang-js">const crypto = require('crypto');
crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, key) => {
if (err) throw err;
console.log(key.toString('hex')); // 'c5e478d...1469e50'
});
</code></pre>
<p>An array of supported digest functions can be retrieved using
<a href="#crypto_crypto_gethashes"><code>crypto.getHashes()</code></a>.</p>
<h3>crypto.pbkdf2Sync(password, salt, iterations, keylen[, digest])<span><a class="mark" href="#crypto_crypto_pbkdf2sync_password_salt_iterations_keylen_digest" id="crypto_crypto_pbkdf2sync_password_salt_iterations_keylen_digest">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.3</span>
</div><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>. If the <code>digest</code> algorithm is not specified,
a default of <code>'sha1'</code> is used.</p>
<p>If an error occurs an Error will be thrown, otherwise the derived key will be
returned as a <a href="buffer.html#buffer_buffer"><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 also be as unique as possible. It is recommended that the
salts are random and their lengths are greater than 16 bytes. See
<a href="http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf">NIST SP 800-132</a> for details.</p>
<p>Example:</p>
<pre><code class="lang-js">const crypto = require('crypto');
const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');
console.log(key.toString('hex')); // 'c5e478d...1469e50'
</code></pre>
<p>An array of supported digest functions can be retrieved using
<a href="#crypto_crypto_gethashes"><code>crypto.getHashes()</code></a>.</p>
<h3>crypto.privateDecrypt(private_key, buffer)<span><a class="mark" href="#crypto_crypto_privatedecrypt_private_key_buffer" id="crypto_crypto_privatedecrypt_private_key_buffer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div><p>Decrypts <code>buffer</code> with <code>private_key</code>.</p>
<p><code>private_key</code> can be an object or a string. If <code>private_key</code> is a string, it is
treated as the key with no passphrase and will use <code>RSA_PKCS1_OAEP_PADDING</code>.
If <code>private_key</code> is an object, it is interpreted as a hash object with the
keys:</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> - 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> - Optional passphrase for the private key</li>
<li><code>padding</code> : An optional padding value, one of the following:<ul>
<li><code>constants.RSA_NO_PADDING</code></li>
<li><code>constants.RSA_PKCS1_PADDING</code></li>
<li><code>constants.RSA_PKCS1_OAEP_PADDING</code></li>
</ul>
</li>
</ul>
<p>All paddings are defined in the <code>constants</code> module.</p>
<h3>crypto.privateEncrypt(private_key, buffer)<span><a class="mark" href="#crypto_crypto_privateencrypt_private_key_buffer" id="crypto_crypto_privateencrypt_private_key_buffer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.1.0</span>
</div><p>Encrypts <code>buffer</code> with <code>private_key</code>.</p>
<p><code>private_key</code> can be an object or a string. If <code>private_key</code> is a string, it is
treated as the key with no passphrase and will use <code>RSA_PKCS1_PADDING</code>.
If <code>private_key</code> is an object, it is interpreted as a hash object with the
keys:</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> - 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> - Optional passphrase for the private key</li>
<li><code>padding</code> : An optional padding value, one of the following:<ul>
<li><code>constants.RSA_NO_PADDING</code></li>
<li><code>constants.RSA_PKCS1_PADDING</code></li>
</ul>
</li>
</ul>
<p>All paddings are defined in the <code>constants</code> module.</p>
<h3>crypto.publicDecrypt(public_key, buffer)<span><a class="mark" href="#crypto_crypto_publicdecrypt_public_key_buffer" id="crypto_crypto_publicdecrypt_public_key_buffer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.1.0</span>
</div><p>Decrypts <code>buffer</code> with <code>public_key</code>.</p>
<p><code>public_key</code> can be an object or a string. If <code>public_key</code> is a string, it is
treated as the key with no passphrase and will use <code>RSA_PKCS1_PADDING</code>.
If <code>public_key</code> is an object, it is interpreted as a hash object with the
keys:</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> - PEM encoded public 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> - Optional passphrase for the private key</li>
<li><code>padding</code> : An optional padding value, one of the following:<ul>
<li><code>constants.RSA_NO_PADDING</code></li>
<li><code>constants.RSA_PKCS1_PADDING</code></li>
<li><code>constants.RSA_PKCS1_OAEP_PADDING</code></li>
</ul>
</li>
</ul>
<p>Because RSA public keys can be derived from private keys, a private key may
be passed instead of a public key.</p>
<p>All paddings are defined in the <code>constants</code> module.</p>
<h3>crypto.publicEncrypt(public_key, buffer)<span><a class="mark" href="#crypto_crypto_publicencrypt_public_key_buffer" id="crypto_crypto_publicencrypt_public_key_buffer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div><p>Encrypts <code>buffer</code> with <code>public_key</code>.</p>
<p><code>public_key</code> can be an object or a string. If <code>public_key</code> is a string, it is
treated as the key with no passphrase and will use <code>RSA_PKCS1_OAEP_PADDING</code>.
If <code>public_key</code> is an object, it is interpreted as a hash object with the
keys:</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> - PEM encoded public 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> - Optional passphrase for the private key</li>
<li><code>padding</code> : An optional padding value, one of the following:<ul>
<li><code>constants.RSA_NO_PADDING</code></li>
<li><code>constants.RSA_PKCS1_PADDING</code></li>
<li><code>constants.RSA_PKCS1_OAEP_PADDING</code></li>
</ul>
</li>
</ul>
<p>Because RSA public keys can be derived from private keys, a private key may
be passed instead of a public key.</p>
<p>All paddings are defined in the <code>constants</code> module.</p>
<h3>crypto.randomBytes(size[, callback])<span><a class="mark" href="#crypto_crypto_randombytes_size_callback" id="crypto_crypto_randombytes_size_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><p>Generates cryptographically strong pseudo-random 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 Error object; otherwise it is null. The
<code>buf</code> argument is a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a> containing the generated bytes.</p>
<pre><code class="lang-js">// Asynchronous
const crypto = require('crypto');
crypto.randomBytes(256, (err, buf) => {
if (err) throw err;
console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
});
</code></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#buffer_buffer"><code>Buffer</code></a>. An error will be thrown if
there is a problem generating the bytes.</p>
<pre><code class="lang-js">// Synchronous
const buf = crypto.randomBytes(256);
console.log(
`${buf.length} bytes of random data: ${buf.toString('hex')}`);
</code></pre>
<p>The <code>crypto.randomBytes()</code> method will block until there is sufficient entropy.
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>
<h3>crypto.setEngine(engine[, flags])<span><a class="mark" href="#crypto_crypto_setengine_engine_flags" id="crypto_crypto_setengine_engine_flags">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.11</span>
</div><p>Load and set the <code>engine</code> for some or all OpenSSL functions (selected by flags).</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 the
<code>constants</code> module):</p>
<ul>
<li><code>ENGINE_METHOD_RSA</code></li>
<li><code>ENGINE_METHOD_DSA</code></li>
<li><code>ENGINE_METHOD_DH</code></li>
<li><code>ENGINE_METHOD_RAND</code></li>
<li><code>ENGINE_METHOD_ECDH</code></li>
<li><code>ENGINE_METHOD_ECDSA</code></li>
<li><code>ENGINE_METHOD_CIPHERS</code></li>
<li><code>ENGINE_METHOD_DIGESTS</code></li>
<li><code>ENGINE_METHOD_STORE</code></li>
<li><code>ENGINE_METHOD_PKEY_METH</code></li>
<li><code>ENGINE_METHOD_PKEY_ASN1_METH</code></li>
<li><code>ENGINE_METHOD_ALL</code></li>
<li><code>ENGINE_METHOD_NONE</code></li>
</ul>
<h2>Notes<span><a class="mark" href="#crypto_notes" id="crypto_notes">#</a></span></h2>
<h3>Legacy Streams API (pre Node.js v0.10)<span><a class="mark" href="#crypto_legacy_streams_api_pre_node_js_v0_10" id="crypto_legacy_streams_api_pre_node_js_v0_10">#</a></span></h3>
<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#buffer_buffer"><code>Buffer</code></a> objects for handling
binary data. As such, the many of the <code>crypto</code> defined classes have methods not
typically found on other Node.js classes that implement the <a href="stream.html#stream_stream">streams</a>
API (e.g. <code>update()</code>, <code>final()</code>, or <code>digest()</code>). Also, many methods accepted
and returned <code>'binary'</code> encoded strings by default rather than Buffers. This
default was changed after Node.js v0.8 to use <a href="buffer.html#buffer_buffer"><code>Buffer</code></a> objects by default
instead.</p>
<h3>Recent ECDH Changes<span><a class="mark" href="#crypto_recent_ecdh_changes" id="crypto_recent_ecdh_changes">#</a></span></h3>
<p>Usage of <code>ECDH</code> with non-dynamically generated key pairs has been simplified.
Now, <a href="#crypto_ecdh_setprivatekey_private_key_encoding"><code>ecdh.setPrivateKey()</code></a> can be called with a preselected private key
and the associated public point (key) will be computed and stored in the object.
This allows code to only store and provide the private part of the EC key pair.
<a href="#crypto_ecdh_setprivatekey_private_key_encoding"><code>ecdh.setPrivateKey()</code></a> now also validates that the private key is valid for
the selected curve.</p>
<p>The <a href="#crypto_ecdh_setpublickey_public_key_encoding"><code>ecdh.setPublicKey()</code></a> method is now deprecated as its inclusion in the
API is not useful. Either a previously stored private key should be set, which
automatically generates the associated public key, or <a href="#crypto_ecdh_generatekeys_encoding_format"><code>ecdh.generateKeys()</code></a>
should be called. The main drawback of using <a href="#crypto_ecdh_setpublickey_public_key_encoding"><code>ecdh.setPublicKey()</code></a> is that
it can be used to put the ECDH key pair into an inconsistent state.</p>
<h3>Support for weak or compromised algorithms<span><a class="mark" href="#crypto_support_for_weak_or_compromised_algorithms" id="crypto_support_for_weak_or_compromised_algorithms">#</a></span></h3>
<p>The <code>crypto</code> module still supports some algorithms which are already
compromised and are not currently recommended for use. The API also allows
the use of ciphers and hashes with a small key size that are considered to be
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="http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar1.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>
<!-- [end-include:crypto.md] -->
<!-- [start-include:debugger.md] -->
<h1>Debugger<span><a class="mark" href="#debugger_debugger" id="debugger_debugger">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><!-- type=misc -->
<p>Node.js includes an out-of-process debugging utility accessible via a
<a href="https://github.com/v8/v8/wiki/Debugging-Protocol">TCP-based protocol</a> and built-in debugging client. To use it, start Node.js
with the <code>debug</code> argument followed by the path to the script to debug; a prompt
will be displayed indicating successful launch of the debugger:</p>
<pre><code>$ node debug myscript.js
< debugger listening on port 5858
connecting... ok
break in /home/indutny/Code/git/indutny/myscript.js:1
1 x = 5;
2 setTimeout(() => {
3 debugger;
debug>
</code></pre><p>Node.js's debugger client is not a full-featured debugger, but simple step and
inspection are possible.</p>
<p>Inserting the statement <code>debugger;</code> into the source code of a script will
enable a breakpoint at that position in the code:</p>
<pre><code class="lang-js">// myscript.js
x = 5;
setTimeout(() => {
debugger;
console.log('world');
}, 1000);
console.log('hello');
</code></pre>
<p>Once the debugger is run, a breakpoint will occur at line 4:</p>
<pre><code>$ node debug myscript.js
< debugger listening on port 5858
connecting... ok
break in /home/indutny/Code/git/indutny/myscript.js:1
1 x = 5;
2 setTimeout(() => {
3 debugger;
debug> cont
< hello
break in /home/indutny/Code/git/indutny/myscript.js:3
1 x = 5;
2 setTimeout(() => {
3 debugger;
4 console.log('world');
5 }, 1000);
debug> next
break in /home/indutny/Code/git/indutny/myscript.js:4
2 setTimeout(() => {
3 debugger;
4 console.log('world');
5 }, 1000);
6 console.log('hello');
debug> repl
Press Ctrl + C to leave debug repl
> x
5
> 2+2
4
debug> next
< world
break in /home/indutny/Code/git/indutny/myscript.js:5
3 debugger;
4 console.log('world');
5 }, 1000);
6 console.log('hello');
7
debug> quit
</code></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>
<h2>Watchers<span><a class="mark" href="#debugger_watchers" id="debugger_watchers">#</a></span></h2>
<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>
<h2>Command reference<span><a class="mark" href="#debugger_command_reference" id="debugger_command_reference">#</a></span></h2>
<h3>Stepping<span><a class="mark" href="#debugger_stepping" id="debugger_stepping">#</a></span></h3>
<div class="signature"><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>
</div><h3>Breakpoints<span><a class="mark" href="#debugger_breakpoints" id="debugger_breakpoints">#</a></span></h3>
<div class="signature"><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
functions body</li>
<li><code>setBreakpoint('script.js', 1)</code>, <code>sb(...)</code> - Set breakpoint on first line of
script.js</li>
<li><code>clearBreakpoint('script.js', 1)</code>, <code>cb(...)</code> - Clear breakpoint in script.js
on line 1</li>
</ul>
</div><p>It is also possible to set a breakpoint in a file (module) that
isn't loaded yet:</p>
<pre><code>$ node debug test/fixtures/break-in-module/main.js
< debugger listening on port 5858
connecting to port 5858... ok
break in test/fixtures/break-in-module/main.js:1
1 var mod = require('./mod.js');
2 mod.hello();
3 mod.hello();
debug> setBreakpoint('mod.js', 23)
Warning: script 'mod.js' was not loaded yet.
1 var mod = require('./mod.js');
2 mod.hello();
3 mod.hello();
debug> c
break in test/fixtures/break-in-module/mod.js:23
21
22 exports.hello = () => {
23 return 'hello from module';
24 };
25
debug>
</code></pre><h3>Information<span><a class="mark" href="#debugger_information" id="debugger_information">#</a></span></h3>
<div class="signature"><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>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> - Execute an expression in debugging script's context</li>
</ul>
</div><h3>Execution control<span><a class="mark" href="#debugger_execution_control" id="debugger_execution_control">#</a></span></h3>
<div class="signature"><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>
</div><h3>Various<span><a class="mark" href="#debugger_various" id="debugger_various">#</a></span></h3>
<div class="signature"><ul>
<li><code>scripts</code> - List all loaded scripts</li>
<li><code>version</code> - Display V8's version</li>
</ul>
</div><h2>Advanced Usage<span><a class="mark" href="#debugger_advanced_usage" id="debugger_advanced_usage">#</a></span></h2>
<p>An alternative way of enabling and accessing the debugger is to start
Node.js with the <code>--debug</code> command-line flag or by signaling an existing
Node.js process with <code>SIGUSR1</code>.</p>
<p>Once a process has been set in debug mode this way, it can be inspected
using the Node.js debugger by either connecting to the <code>pid</code> of the running
process or via URI reference to the listening debugger:</p>
<ul>
<li><code>node debug -p <pid></code> - Connects to the process via the <code>pid</code></li>
<li><code>node debug <URI></code> - Connects to the process via the URI such as
localhost:5858</li>
</ul>
<!-- [end-include:debugger.md] -->
<!-- [start-include:dgram.md] -->
<h1>UDP / Datagram Sockets<span><a class="mark" href="#dgram_udp_datagram_sockets" id="dgram_udp_datagram_sockets">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><!-- name=dgram -->
<p>The <code>dgram</code> module provides an implementation of UDP Datagram sockets.</p>
<pre><code class="lang-js">const dgram = require('dgram');
const server = dgram.createSocket('udp4');
server.on('error', (err) => {
console.log(`server error:\n${err.stack}`);
server.close();
});
server.on('message', (msg, rinfo) => {
console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
});
server.on('listening', () => {
var address = server.address();
console.log(`server listening ${address.address}:${address.port}`);
});
server.bind(41234);
// server listening 0.0.0.0:41234
</code></pre>
<h2>Class: dgram.Socket<span><a class="mark" href="#dgram_class_dgram_socket" id="dgram_class_dgram_socket">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div><p>The <code>dgram.Socket</code> object is an <a href="events.html#events_class_eventemitter"><code>EventEmitter</code></a> that encapsulates the
datagram functionality.</p>
<p>New instances of <code>dgram.Socket</code> are created using <a href="#dgram_dgram_createsocket_options_callback"><code>dgram.createSocket()</code></a>.
The <code>new</code> keyword is not to be used to create <code>dgram.Socket</code> instances.</p>
<h3>Event: 'close'<span><a class="mark" href="#dgram_event_close" id="dgram_event_close">#</a></span></h3>
<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="#dgram_socket_close_callback"><code>close()</code></a>.
Once triggered, no new <code>'message'</code> events will be emitted on this socket.</p>
<h3>Event: 'error'<span><a class="mark" href="#dgram_event_error" id="dgram_event_error">#</a></span></h3>
<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 Error object.</p>
<h3>Event: 'listening'<span><a class="mark" href="#dgram_event_listening" id="dgram_event_listening">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div><p>The <code>'listening'</code> event is emitted whenever a socket begins listening for
datagram messages. This occurs as soon as UDP sockets are created.</p>
<h3>Event: 'message'<span><a class="mark" href="#dgram_event_message" id="dgram_event_message">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</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="buffer.html#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>
<h3>socket.addMembership(multicastAddress[, multicastInterface])<span><a class="mark" href="#dgram_socket_addmembership_multicastaddress_multicastinterface" id="dgram_socket_addmembership_multicastaddress_multicastinterface">#</a></span></h3>
<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>, Optional</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>
<h3>socket.address()<span><a class="mark" href="#dgram_socket_address" id="dgram_socket_address">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div><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>
<h3>socket.bind([port][, address][, callback])<span><a class="mark" href="#dgram_socket_bind_port_address_callback" id="dgram_socket_bind_port_address_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</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> - Integer, Optional</li>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a>, Optional</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, Optional. 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>Note that 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="errors.html#errors_class_error"><code>Error</code></a> may be thrown.</p>
<p>Example of a UDP server listening on port 41234:</p>
<pre><code class="lang-js">const dgram = require('dgram');
const server = dgram.createSocket('udp4');
server.on('error', (err) => {
console.log(`server error:\n${err.stack}`);
server.close();
});
server.on('message', (msg, rinfo) => {
console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`);
});
server.on('listening', () => {
var address = server.address();
console.log(`server listening ${address.address}:${address.port}`);
});
server.bind(41234);
// server listening 0.0.0.0:41234
</code></pre>
<h3>socket.bind(options[, callback])<span><a class="mark" href="#dgram_socket_bind_options_callback" id="dgram_socket_bind_options_callback">#</a></span></h3>
<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"><Number></a> - Optional.</li>
<li><code>address</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> - Optional.</li>
<li><code>exclusive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> - Optional.</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> - Optional.</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>Note that 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
use 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="errors.html#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="lang-js">socket.bind({
address: 'localhost',
port: 8000,
exclusive: true
});
</code></pre>
<h3>socket.close([callback])<span><a class="mark" href="#dgram_socket_close_callback" id="dgram_socket_close_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div><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="#net_event_close"><code>'close'</code></a> event.</p>
<h3>socket.dropMembership(multicastAddress[, multicastInterface])<span><a class="mark" href="#dgram_socket_dropmembership_multicastaddress_multicastinterface" id="dgram_socket_dropmembership_multicastaddress_multicastinterface">#</a></span></h3>
<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>, Optional</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>
<h3>socket.send(buf, offset, length, port, address[, callback])<span><a class="mark" href="#dgram_socket_send_buf_offset_length_port_address_callback" id="dgram_socket_send_buf_offset_length_port_address_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div><ul>
<li><code>buf</code> <a href="buffer.html#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> 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"><Number></a> Integer. 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"><Number></a> Integer. 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"><Number></a> Integer. 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 hostname 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. Optional.</li>
</ul>
<p>Broadcasts a datagram on the socket. The destination <code>port</code> and <code>address</code> must
be specified.</p>
<p>The <code>buf</code> argument is a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a> object containing the message. 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. With messages that
contain multi-byte characters, <code>offset</code> and <code>length</code> will be calculated with
respect to <a href="buffer.html#buffer_class_method_buffer_bytelength_string_encoding">byte length</a> and not the character position.</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 the <code>address</code> is not
specified or is an empty string, <code>'0.0.0.0'</code> or <code>'::0'</code> will be used instead.
It is possible, depending on the network configuration, that these defaults
may not work; accordingly, it is best to be explicit about the destination
address.</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.
Note that 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>Example of sending a UDP packet to a random port on <code>localhost</code>;</p>
<pre><code class="lang-js">const dgram = require('dgram');
const message = new Buffer('Some bytes');
const client = dgram.createSocket('udp4');
client.send(message, 0, message.length, 41234, 'localhost', (err) => {
client.close();
});
</code></pre>
<p><strong>A Note about UDP datagram size</strong></p>
<p>The maximum size of an <code>IPv4/v6</code> datagram depends on the <code>MTU</code>
(<em>Maximum Transmission Unit</em>) and on the <code>Payload Length</code> field size.</p>
<ul>
<li><p>The <code>Payload Length</code> field is <code>16 bits</code> wide, which means that a normal
payload exceed 64K octets <em>including</em> 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, <code>IPv4</code> mandates a minimum <code>MTU</code> of <code>68</code>
octets, while the recommended <code>MTU</code> for IPv4 is <code>576</code> (typically recommended
as the <code>MTU</code> for dial-up type applications), whether they arrive whole or in
fragments.</p>
<p>For <code>IPv6</code>, the minimum <code>MTU</code> is <code>1280</code> octets, however, the mandatory minimum
fragment reassembly buffer size is <code>1500</code> octets. The value of <code>68</code> octets is
very small, since most current link layer technologies, like Ethernet, have a
minimum <code>MTU</code> of <code>1500</code>.</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>
<h3>socket.setBroadcast(flag)<span><a class="mark" href="#dgram_socket_setbroadcast_flag" id="dgram_socket_setbroadcast_flag">#</a></span></h3>
<div class="signature"><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>
</div><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>
<h3>socket.setMulticastLoopback(flag)<span><a class="mark" href="#dgram_socket_setmulticastloopback_flag" id="dgram_socket_setmulticastloopback_flag">#</a></span></h3>
<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>
<h3>socket.setMulticastTTL(ttl)<span><a class="mark" href="#dgram_socket_setmulticastttl_ttl" id="dgram_socket_setmulticastttl_ttl">#</a></span></h3>
<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"><Number></a> Integer</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 argument passed to to <code>socket.setMulticastTTL()</code> is a number of hops
between 0 and 255. The default on most systems is <code>1</code> but can vary.</p>
<h3>socket.setTTL(ttl)<span><a class="mark" href="#dgram_socket_setttl_ttl" id="dgram_socket_setttl_ttl">#</a></span></h3>
<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"><Number></a> Integer</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 argument to <code>socket.setTTL()</code> is a number of hops between 1 and 255.
The default on most systems is 64 but can vary.</p>
<h3>socket.ref()<span><a class="mark" href="#dgram_socket_ref" id="dgram_socket_ref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div><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>
<h3>socket.unref()<span><a class="mark" href="#dgram_socket_unref" id="dgram_socket_unref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div><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 addition effect.</p>
<p>The <code>socket.unref()</code> method returns a reference to the socket so calls can be
chained.</p>
<h3>Change to asynchronous <code>socket.bind()</code> behavior<span><a class="mark" href="#dgram_change_to_asynchronous_socket_bind_behavior" id="dgram_change_to_asynchronous_socket_bind_behavior">#</a></span></h3>
<p>As of Node.js v0.10, <a href="#dgram_socket_bind_options_callback"><code>dgram.Socket#bind()</code></a> changed to an asynchronous
execution model. Legacy code that assumes synchronous behavior, as in the
following example:</p>
<pre><code class="lang-js">const s = dgram.createSocket('udp4');
s.bind(1234);
s.addMembership('224.0.0.114');
</code></pre>
<p>Must be changed to pass a callback function to the <a href="#dgram_socket_bind_options_callback"><code>dgram.Socket#bind()</code></a>
function:</p>
<pre><code class="lang-js">const s = dgram.createSocket('udp4');
s.bind(1234, () => {
s.addMembership('224.0.0.114');
});
</code></pre>
<h2><code>dgram</code> module functions<span><a class="mark" href="#dgram_dgram_module_functions" id="dgram_dgram_module_functions">#</a></span></h2>
<h3>dgram.createSocket(options[, callback])<span><a class="mark" href="#dgram_dgram_createsocket_options_callback" id="dgram_dgram_createsocket_options_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.13</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>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="dgram.html#dgram_class_dgram_socket" class="type"><dgram.Socket></a></li>
</ul>
<p>Creates a <code>dgram.Socket</code> object. The <code>options</code> argument is an object that
should contain a <code>type</code> field of either <code>udp4</code> or <code>udp6</code> and an optional
boolean <code>reuseAddr</code> field.</p>
<p>When <code>reuseAddr</code> is <code>true</code> <a href="#dgram_socket_bind_port_address_callback"><code>socket.bind()</code></a> will reuse the address, even if
another process has already bound a socket on it. <code>reuseAddr</code> defaults to
<code>false</code>. The optional <code>callback</code> function is added as a listener for <code>'message'</code>
events.</p>
<p>Once the socket is created, calling <a href="#dgram_socket_bind_port_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="#dgram_socket_bind_port_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="#dgram_socket_address"><code>socket.address().address</code></a> and <a href="#dgram_socket_address"><code>socket.address().port</code></a>.</p>
<h3>dgram.createSocket(type[, callback])<span><a class="mark" href="#dgram_dgram_createsocket_type_callback" id="dgram_dgram_createsocket_type_callback">#</a></span></h3>
<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 'udp4' or 'udp6'</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.
Optional</li>
<li>Returns: <a href="dgram.html#dgram_class_dgram_socket" class="type"><dgram.Socket></a></li>
</ul>
<p>Creates a <code>dgram.Socket</code> object of the specified <code>type</code>. The <code>type</code> argument
can be either <code>udp4</code> or <code>udp6</code>. An optional <code>callback</code> function can be passed
which is added as a listener for <code>'message'</code> events.</p>
<p>Once the socket is created, calling <a href="#dgram_socket_bind_port_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="#dgram_socket_bind_port_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="#dgram_socket_address"><code>socket.address().address</code></a> and <a href="#dgram_socket_address"><code>socket.address().port</code></a>.</p>
<!-- [end-include:dgram.md] -->
<!-- [start-include:dns.md] -->
<h1>DNS<span><a class="mark" href="#dns_dns" id="dns_dns">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>The <code>dns</code> module contains functions belonging to two different categories:</p>
<p>1) Functions that use the underlying operating system facilities to perform
name resolution, and that do not necessarily perform any network communication.
This category contains only one function: <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>. <strong>Developers
looking to perform name resolution in the same way that other applications on
the same operating system behave should use <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</strong></p>
<p>For example, looking up <code>iana.org</code>.</p>
<pre><code class="lang-js">const dns = require('dns');
dns.lookup('nodejs.org', (err, addresses, family) => {
console.log('addresses:', addresses);
});
// address: "192.0.43.8" family: IPv4
</code></pre>
<p>2) Functions that connect to an actual DNS server to perform name resolution,
and that <em>always</em> use the network to perform DNS queries. This category
contains all functions in the <code>dns</code> module <em>except</em> <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>. These
functions do not use the same set of configuration files used by
<a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> (e.g. <code>/etc/hosts</code>). These functions should be used by
developers who do not want to use the underlying operating system's facilities
for name resolution, and instead want to <em>always</em> perform DNS queries.</p>
<p>Below is an example that resolves <code>'archive.org'</code> then reverse resolves the IP
addresses that are returned.</p>
<pre><code class="lang-js">const dns = require('dns');
dns.resolve4('archive.org', (err, addresses) => {
if (err) throw err;
console.log(`addresses: ${JSON.stringify(addresses)}`);
addresses.forEach((a) => {
dns.reverse(a, (err, hostnames) => {
if (err) {
throw err;
}
console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`);
});
});
});
</code></pre>
<p>There are subtle consequences in choosing one over the other, please consult
the <a href="#dns_implementation_considerations">Implementation considerations section</a> for more information.</p>
<h2>dns.getServers()<span><a class="mark" href="#dns_dns_getservers" id="dns_dns_getservers">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.3</span>
</div><p>Returns an array of IP address strings that are being used for name
resolution.</p>
<h2>dns.lookup(hostname[, options], callback)<span><a class="mark" href="#dns_dns_lookup_hostname_options_callback" id="dns_dns_lookup_hostname_options_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>Resolves a hostname (e.g. <code>'nodejs.org'</code>) into the first found A (IPv4) or
AAAA (IPv6) record. <code>options</code> can be an object or integer. If <code>options</code> is
not provided, then IPv4 and IPv6 addresses are both valid. If <code>options</code> is
an integer, then it must be <code>4</code> or <code>6</code>.</p>
<p>Alternatively, <code>options</code> can be an object containing these properties:</p>
<ul>
<li><code>family</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> - The record family. If present, must be the integer
<code>4</code> or <code>6</code>. If not provided, both IP v4 and v6 addresses are accepted.</li>
<li><code>hints</code>: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> - If present, it should be one or more of the supported
<code>getaddrinfo</code> flags. If <code>hints</code> is not provided, then no flags are passed to
<code>getaddrinfo</code>. Multiple flags can be passed through <code>hints</code> by bitwise
<code>OR</code>ing their values.
See <a href="#dns_supported_getaddrinfo_flags">supported <code>getaddrinfo</code> flags</a> for more information on supported
flags.</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. Defaults to <code>false</code>.</li>
</ul>
<p>All properties are optional. An example usage of options is shown below.</p>
<pre><code>{
family: 4,
hints: dns.ADDRCONFIG | dns.V4MAPPED,
all: false
}
</code></pre><p>The <code>callback</code> function has arguments <code>(err, address, family)</code>. <code>address</code> is a
string representation of an IPv4 or IPv6 address. <code>family</code> is either the
integer <code>4</code> or <code>6</code> and denotes the family of <code>address</code> (not necessarily the
value initially passed to <code>lookup</code>).</p>
<p>With the <code>all</code> option set to <code>true</code>, the arguments 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="errors.html#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>'ENOENT'</code> not only when
the hostname 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="#dns_implementation_considerations">Implementation considerations section</a> before using
<code>dns.lookup()</code>.</p>
<p>Example usage:</p>
<pre><code class="lang-js">const dns = require('dns');
const options = {
family: 6,
hints: dns.ADDRCONFIG | dns.V4MAPPED,
};
dns.lookup('example.com', options, (err, address, family) =>
console.log('address: %j family: IPv%s', address, family));
// address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6
// When options.all is true, the result will be an Array.
options.all = true;
dns.lookup('example.com', options, (err, addresses) =>
console.log('addresses: %j', addresses));
// addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}]
</code></pre>
<h3>Supported getaddrinfo flags<span><a class="mark" href="#dns_supported_getaddrinfo_flags" id="dns_supported_getaddrinfo_flags">#</a></span></h3>
<p>The following flags can be passed as hints to <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</p>
<ul>
<li><code>dns.ADDRCONFIG</code>: Returned address types are determined by the types
of addresses supported by the current system. For example, IPv4 addresses
are only returned if the current system has at least one IPv4 address
configured. Loopback addresses are not considered.</li>
<li><code>dns.V4MAPPED</code>: If the IPv6 family was specified, but no IPv6 addresses were
found, then return IPv4 mapped IPv6 addresses. Note that it is not supported
on some operating systems (e.g FreeBSD 10.1).</li>
</ul>
<h2>dns.lookupService(address, port, callback)<span><a class="mark" href="#dns_dns_lookupservice_address_port_callback" id="dns_dns_lookupservice_address_port_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div><p>Resolves the given <code>address</code> and <code>port</code> into a hostname and service using
the operating system's underlying <code>getnameinfo</code> implementation.</p>
<p>The callback has arguments <code>(err, hostname, service)</code>. The <code>hostname</code> and
<code>service</code> arguments are strings (e.g. <code>'localhost'</code> and <code>'http'</code> respectively).</p>
<p>On error, <code>err</code> is an <a href="errors.html#errors_class_error"><code>Error</code></a> object, where <code>err.code</code> is the error code.</p>
<pre><code class="lang-js">const dns = require('dns');
dns.lookupService('127.0.0.1', 22, (err, hostname, service) => {
console.log(hostname, service);
// Prints: localhost ssh
});
</code></pre>
<h2>dns.resolve(hostname[, rrtype], callback)<span><a class="mark" href="#dns_dns_resolve_hostname_rrtype_callback" id="dns_dns_resolve_hostname_rrtype_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.27</span>
</div><p>Uses the DNS protocol to resolve a hostname (e.g. <code>'nodejs.org'</code>) into an
array of the record types specified by <code>rrtype</code>.</p>
<p>Valid values for <code>rrtype</code> are:</p>
<ul>
<li><code>'A'</code> - IPV4 addresses, default</li>
<li><code>'AAAA'</code> - IPV6 addresses</li>
<li><code>'MX'</code> - mail exchange records</li>
<li><code>'TXT'</code> - text records</li>
<li><code>'SRV'</code> - SRV records</li>
<li><code>'PTR'</code> - used for reverse IP lookups</li>
<li><code>'NS'</code> - name server records</li>
<li><code>'CNAME'</code> - canonical name records</li>
<li><code>'SOA'</code> - start of authority record</li>
<li><code>'NAPTR'</code> - name authority pointer record</li>
</ul>
<p>The <code>callback</code> function has arguments <code>(err, addresses)</code>. When successful,
<code>addresses</code> will be an array, except when resolving an SOA record which returns
an object structured in the same manner as one returned by the
<a href="#dns_dns_resolvesoa_hostname_callback"><code>dns.resolveSoa()</code></a> method. The type of each item in <code>addresses</code> is
determined by the record type, and described in the documentation for the
corresponding lookup methods.</p>
<p>On error, <code>err</code> is an <a href="errors.html#errors_class_error"><code>Error</code></a> object, where <code>err.code</code> is
one of the error codes listed <a href="#dns_error_codes">here</a>.</p>
<h2>dns.resolve4(hostname, callback)<span><a class="mark" href="#dns_dns_resolve4_hostname_callback" id="dns_dns_resolve4_hostname_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div><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>
<h2>dns.resolve6(hostname, callback)<span><a class="mark" href="#dns_dns_resolve6_hostname_callback" id="dns_dns_resolve6_hostname_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div><p>Uses the DNS protocol to resolve a 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>
<h2>dns.resolveCname(hostname, callback)<span><a class="mark" href="#dns_dns_resolvecname_hostname_callback" id="dns_dns_resolvecname_hostname_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.2</span>
</div><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>
<h2>dns.resolveMx(hostname, callback)<span><a class="mark" href="#dns_dns_resolvemx_hostname_callback" id="dns_dns_resolvemx_hostname_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.27</span>
</div><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>
<h2>dns.resolveNaptr(hostname, callback)<span><a class="mark" href="#dns_dns_resolvenaptr_hostname_callback" id="dns_dns_resolvenaptr_hostname_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.9.12</span>
</div><p>Uses the DNS protocol to resolve regular expression based records (<code>NAPTR</code>
records) for the <code>hostname</code>. The <code>callback</code> function has arguments
<code>(err, addresses)</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>
<p>For example:</p>
<pre><code class="lang-js">{
flags: 's',
service: 'SIP+D2U',
regexp: '',
replacement: '_sip._udp.example.com',
order: 30,
preference: 100
}
</code></pre>
<h2>dns.resolveNs(hostname, callback)<span><a class="mark" href="#dns_dns_resolvens_hostname_callback" id="dns_dns_resolvens_hostname_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><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>
<h2>dns.resolveSoa(hostname, callback)<span><a class="mark" href="#dns_dns_resolvesoa_hostname_callback" id="dns_dns_resolvesoa_hostname_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.10</span>
</div><p>Uses the DNS protocol to resolve a start of authority record (<code>SOA</code> record) for
the <code>hostname</code>. The <code>addresses</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>
<pre><code>{
nsname: 'ns.example.com',
hostmaster: 'root.example.com',
serial: 2013101809,
refresh: 10000,
retry: 2400,
expire: 604800,
minttl: 3600
}
</code></pre><h2>dns.resolveSrv(hostname, callback)<span><a class="mark" href="#dns_dns_resolvesrv_hostname_callback" id="dns_dns_resolvesrv_hostname_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.27</span>
</div><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>
<pre><code>{
priority: 10,
weight: 5,
port: 21223,
name: 'service.example.com'
}
</code></pre><h2>dns.resolveTxt(hostname, callback)<span><a class="mark" href="#dns_dns_resolvetxt_hostname_callback" id="dns_dns_resolvetxt_hostname_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.27</span>
</div><p>Uses the DNS protocol to resolve text queries (<code>TXT</code> records) for the
<code>hostname</code>. The <code>addresses</code> argument passed to the <code>callback</code> function is
is a two-dimentional 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>
<h2>dns.reverse(ip, callback)<span><a class="mark" href="#dns_dns_reverse_ip_callback" id="dns_dns_reverse_ip_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div><p>Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an
array of hostnames.</p>
<p>The <code>callback</code> function has arguments <code>(err, hostnames)</code>, where <code>hostnames</code>
is an array of resolved hostnames for the given <code>ip</code>.</p>
<p>On error, <code>err</code> is an <a href="errors.html#errors_class_error"><code>Error</code></a> object, where <code>err.code</code> is
one of the <a href="#dns_error_codes">DNS error codes</a>.</p>
<h2>dns.setServers(servers)<span><a class="mark" href="#dns_dns_setservers_servers" id="dns_dns_setservers_servers">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.3</span>
</div><p>Sets the IP addresses of the servers to be used when resolving. The <code>servers</code>
argument is an array of IPv4 or IPv6 addresses.</p>
<p>If a port specified on the address it will be removed.</p>
<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>
<h2>Error codes<span><a class="mark" href="#dns_error_codes" id="dns_error_codes">#</a></span></h2>
<p>Each DNS query can return one of the following error codes:</p>
<ul>
<li><code>dns.NODATA</code>: DNS server returned 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 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 hostname.</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 hostname 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 iphlpapi.dll.</li>
<li><code>dns.ADDRGETNETWORKPARAMS</code>: Could not find GetNetworkParams function.</li>
<li><code>dns.CANCELLED</code>: DNS query cancelled.</li>
</ul>
<h2>Implementation considerations<span><a class="mark" href="#dns_implementation_considerations" id="dns_implementation_considerations">#</a></span></h2>
<p>Although <a href="dns.html#dns_dns_lookup_hostname_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>
<h3><code>dns.lookup()</code><span><a class="mark" href="#dns_dns_lookup" id="dns_dns_lookup">#</a></span></h3>
<p>Under the hood, <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> uses the same operating system facilities
as most other programs. For instance, <a href="dns.html#dns_dns_lookup_hostname_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="dns.html#dns_dns_lookup_hostname_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">nsswitch.conf(5)</a> and/or <a href="http://man7.org/linux/man-pages/man5/resolv.conf.5.html">resolv.conf(5)</a>,
but note that changing these files will change the behavior of <em>all other
programs running on the same operating system</em>.</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">getaddrinfo(3)</a> that
runs on libuv's threadpool. Because libuv's threadpool has a fixed size, it
means that if for whatever reason the call to <a href="http://man7.org/linux/man-pages/man3/getaddrinfo.3.html">getaddrinfo(3)</a> takes a long
time, other operations that could run on libuv's threadpool (such as filesystem
operations) 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). For more information on libuv's threadpool, see
<a href="http://docs.libuv.org/en/latest/threadpool.html">the official libuv documentation</a>.</p>
<h3><code>dns.resolve()</code>, <code>dns.resolve*()</code> and <code>dns.reverse()</code><span><a class="mark" href="#dns_dns_resolve_dns_resolve_and_dns_reverse" id="dns_dns_resolve_dns_resolve_and_dns_reverse">#</a></span></h3>
<p>These functions are implemented quite differently than <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>. They
do not use <a href="http://man7.org/linux/man-pages/man3/getaddrinfo.3.html">getaddrinfo(3)</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="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a> can have.</p>
<p>They do not use the same set of configuration files than what <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>
uses. For instance, <em>they do not use the configuration from <code>/etc/hosts</code></em>.</p>
<!-- [end-include:dns.md] -->
<!-- [start-include:domain.md] -->
<h1>Domain<span><a class="mark" href="#domain_domain" id="domain_domain">#</a></span></h1>
<pre class="api_stability api_stability_0">Stability: 0 - Deprecated</pre><p><strong>This module is pending deprecation</strong>. Once a replacement API has been
finalized, this module will be fully deprecated. Most end users 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>
<h2>Warning: Don't Ignore Errors!<span><a class="mark" href="#domain_warning_don_t_ignore_errors" id="domain_warning_don_t_ignore_errors">#</a></span></h2>
<!-- type=misc -->
<p>Domain error handlers are not a substitute for closing down your
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 you 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, you might have many
connections open, 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 master 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="lang-js">// XXX WARNING! BAD IDEA!
const d = require('domain').create();
d.on('error', (er) => {
// The error won't crash the process, but what it does is worse!
// Though we've prevented abrupt process restarting, we are leaking
// resources like crazy if this ever happens.
// This is no better than process.on('uncaughtException')!
console.log(`error, but oh well ${er.message}`);
});
d.run(() => {
require('http').createServer((req, res) => {
handleRequest(req, res);
}).listen(PORT);
});
</code></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="lang-js">// Much better!
const cluster = require('cluster');
const PORT = +process.env.PORT || 1337;
if (cluster.isMaster) {
// In real life, you'd probably use more than just 2 workers,
// and perhaps not put the master and worker in the same file.
//
// You can also of course get a bit fancier about logging, and
// implement whatever custom logic you need to prevent DoS
// attacks and other bad behavior.
//
// See the options in the cluster documentation.
//
// The important thing is that the master does very little,
// increasing our resilience to unexpected errors.
cluster.fork();
cluster.fork();
cluster.on('disconnect', (worker) => {
console.error('disconnect!');
cluster.fork();
});
} else {
// the worker
//
// This is where we put our bugs!
const domain = require('domain');
// See the cluster documentation for more details about using
// worker processes to serve requests. How it works, caveats, etc.
const server = require('http').createServer((req, res) => {
const d = domain.create();
d.on('error', (er) => {
console.error(`error ${er.stack}`);
// Note: we're in dangerous territory!
// By definition, something unexpected occurred,
// which we probably didn't want.
// Anything can happen now! Be very careful!
try {
// make sure we close down within 30 seconds
const killtimer = setTimeout(() => {
process.exit(1);
}, 30000);
// But don't keep the process open just for that!
killtimer.unref();
// stop taking new requests.
server.close();
// Let the master know we're dead. This will trigger a
// 'disconnect' in the cluster master, and then it will fork
// a new worker.
cluster.worker.disconnect();
// try to send an error to the request that triggered the problem
res.statusCode = 500;
res.setHeader('content-type', 'text/plain');
res.end('Oops, there was a problem!\n');
} catch (er2) {
// oh well, not much we can do at this point.
console.error(`Error sending 500! ${er2.stack}`);
}
});
// Because req and res were created before this domain existed,
// we need to explicitly add them.
// See the explanation of implicit vs explicit binding below.
d.add(req);
d.add(res);
// Now run the handler function in the domain.
d.run(() => {
handleRequest(req, res);
});
});
server.listen(PORT);
}
// This part isn't important. Just an example routing thing.
// You'd put your fancy application logic here.
function handleRequest(req, res) {
switch (req.url) {
case '/error':
// We do some async stuff, and then...
setTimeout(() => {
// Whoops!
flerb.bark();
});
break;
default:
res.end('ok');
}
}
</code></pre>
<h2>Additions to Error objects<span><a class="mark" href="#domain_additions_to_error_objects" id="domain_additions_to_error_objects">#</a></span></h2>
<!-- type=misc -->
<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>
<h2>Implicit Binding<span><a class="mark" href="#domain_implicit_binding" id="domain_implicit_binding">#</a></span></h2>
<!--type=misc-->
<p>If domains are in use, then all <strong>new</strong> EventEmitter 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 lowlevel event loop requests (such as
to fs.open, 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, Domain 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>If you <em>want</em> to nest Domain objects as children of a parent Domain,
then you must explicitly add them.</p>
<p>Implicit binding routes thrown errors and <code>'error'</code> events to the
Domain's <code>'error'</code> event, but does not register the EventEmitter on the
Domain, so <a href="#domain_domain_dispose"><code>domain.dispose()</code></a> will not shut down the EventEmitter.
Implicit binding only takes care of thrown errors and <code>'error'</code> events.</p>
<h2>Explicit Binding<span><a class="mark" href="#domain_explicit_binding" id="domain_explicit_binding">#</a></span></h2>
<!--type=misc-->
<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>
<p>For example:</p>
<pre><code class="lang-js">// create a top-level domain for the server
const domain = require('domain');
const http = require('http');
const serverDomain = domain.create();
serverDomain.run(() => {
// server is created in the scope of serverDomain
http.createServer((req, res) => {
// req and res are also created in the scope of serverDomain
// however, we'd prefer to have a separate domain for each request.
// create it first thing, and add req and res to it.
const reqd = domain.create();
reqd.add(req);
reqd.add(res);
reqd.on('error', (er) => {
console.error('Error', er, req.url);
try {
res.writeHead(500);
res.end('Error occurred, sorry.');
} catch (er2) {
console.error('Error sending 500', er2, req.url);
}
});
}).listen(1337);
});
</code></pre>
<h2>domain.create()<span><a class="mark" href="#domain_domain_create" id="domain_domain_create">#</a></span></h2>
<div class="signature"><ul>
<li>Returns: <span class="type"><Domain></span></li>
</ul>
</div><p>Returns a new Domain object.</p>
<h2>Class: Domain<span><a class="mark" href="#domain_class_domain" id="domain_class_domain">#</a></span></h2>
<p>The Domain class encapsulates the functionality of routing errors and
uncaught exceptions to the active Domain object.</p>
<p>Domain is a child class of <a href="events.html#events_class_eventemitter"><code>EventEmitter</code></a>. To handle the errors that it
catches, listen to its <code>'error'</code> event.</p>
<h3>domain.run(fn[, arg][, ...])<span><a class="mark" href="#domain_domain_run_fn_arg" id="domain_domain_run_fn_arg">#</a></span></h3>
<div class="signature"><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>
</ul>
</div><p>Run the supplied function in the context of the domain, implicitly
binding all event emitters, timers, and lowlevel 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>
<p>Example:</p>
<pre><code class="lang-js">const domain = require('domain');
const fs = require('fs');
const d = domain.create();
d.on('error', (er) => {
console.error('Caught error!', er);
});
d.run(() => {
process.nextTick(() => {
setTimeout(() => { // simulating some various async stuff
fs.open('non-existent file', 'r', (er, fd) => {
if (er) throw er;
// proceed...
});
}, 100);
});
});
</code></pre>
<p>In this example, the <code>d.on('error')</code> handler will be triggered, rather
than crashing the program.</p>
<h3>domain.members<span><a class="mark" href="#domain_domain_members" id="domain_domain_members">#</a></span></h3>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
</div><p>An array of timers and event emitters that have been explicitly added
to the domain.</p>
<h3>domain.add(emitter)<span><a class="mark" href="#domain_domain_add_emitter" id="domain_domain_add_emitter">#</a></span></h3>
<div class="signature"><ul>
<li><code>emitter</code> <a href="events.html#events_class_events_eventemitter" class="type"><EventEmitter></a> | <a href="timers.html#timers_timers" class="type"><Timer></a> emitter or timer to be added to the domain</li>
</ul>
</div><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="timers.html#timers_setinterval_callback_delay_arg"><code>setInterval()</code></a> and
<a href="timers.html#timers_settimeout_callback_delay_arg"><code>setTimeout()</code></a>. If their callback function throws, it will be caught by
the domain 'error' handler.</p>
<p>If the Timer or EventEmitter was already bound to a domain, it is removed
from that one, and bound to this one instead.</p>
<h3>domain.remove(emitter)<span><a class="mark" href="#domain_domain_remove_emitter" id="domain_domain_remove_emitter">#</a></span></h3>
<div class="signature"><ul>
<li><code>emitter</code> <a href="events.html#events_class_events_eventemitter" class="type"><EventEmitter></a> | <a href="timers.html#timers_timers" class="type"><Timer></a> emitter or timer to be removed from the domain</li>
</ul>
</div><p>The opposite of <a href="#domain_domain_add_emitter"><code>domain.add(emitter)</code></a>. Removes domain handling from the
specified emitter.</p>
<h3>domain.bind(callback)<span><a class="mark" href="#domain_domain_bind_callback" id="domain_domain_bind_callback">#</a></span></h3>
<div class="signature"><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>
</div><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>
<h4>Example<span><a class="mark" href="#domain_example" id="domain_example">#</a></span></h4>
<pre><code class="lang-js">const d = domain.create();
function readSomeFile(filename, cb) {
fs.readFile(filename, 'utf8', d.bind((er, data) => {
// if this throws, it will also be passed to the domain
return cb(er, data ? JSON.parse(data) : null);
}));
}
d.on('error', (er) => {
// an error occurred somewhere.
// if we throw it now, it will crash the program
// with the normal line number and stack message.
});
</code></pre>
<h3>domain.intercept(callback)<span><a class="mark" href="#domain_domain_intercept_callback" id="domain_domain_intercept_callback">#</a></span></h3>
<div class="signature"><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>
</div><p>This method is almost identical to <a href="#domain_domain_bind_callback"><code>domain.bind(callback)</code></a>. However, in
addition to catching thrown errors, it will also intercept <a href="errors.html#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>
<h4>Example<span><a class="mark" href="#domain_example_1" id="domain_example_1">#</a></span></h4>
<pre><code class="lang-js">const d = domain.create();
function readSomeFile(filename, cb) {
fs.readFile(filename, 'utf8', d.intercept((data) => {
// note, the first argument is never passed to the
// callback since it is assumed to be the 'Error' argument
// and thus intercepted by the domain.
// if this throws, it will also be passed to the domain
// so the error-handling logic can be moved to the 'error'
// event on the domain instead of being repeated throughout
// the program.
return cb(null, JSON.parse(data));
}));
}
d.on('error', (er) => {
// an error occurred somewhere.
// if we throw it now, it will crash the program
// with the normal line number and stack message.
});
</code></pre>
<h3>domain.enter()<span><a class="mark" href="#domain_domain_enter" id="domain_domain_enter">#</a></span></h3>
<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="#domain_domain_exit"><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>
<p>If the domain on which <code>enter</code> is called has been disposed, <code>enter</code> will return
without setting the domain.</p>
<h3>domain.exit()<span><a class="mark" href="#domain_domain_exit" id="domain_domain_exit">#</a></span></h3>
<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>
<p>If the domain on which <code>exit</code> is called has been disposed, <code>exit</code> will return
without exiting the domain.</p>
<h3>domain.dispose()<span><a class="mark" href="#domain_domain_dispose" id="domain_domain_dispose">#</a></span></h3>
<pre class="api_stability api_stability_0">Stability: 0 - Deprecated. Please recover from failed IO actions explicitly via error event handlers set on the domain.</pre><p>Once <code>dispose</code> has been called, the domain will no longer be used by callbacks
bound into the domain via <code>run</code>, <code>bind</code>, or <code>intercept</code>, and a <code>'dispose'</code> event
is emitted.</p>
<!-- [end-include:domain.md] -->
<!-- [start-include:errors.md] -->
<h1>Errors<span><a class="mark" href="#errors_errors" id="errors_errors">#</a></span></h1>
<!--type=misc-->
<p>Applications running in Node.js will generally experience four categories of
errors:</p>
<ul>
<li>Standard JavaScript errors such as:<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/EvalError" class="type"><EvalError></a> : thrown when a call to <code>eval()</code> fails.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError" class="type"><SyntaxError></a> : thrown in response to improper JavaScript language
syntax.</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RangeError" class="type"><RangeError></a> : thrown when a value is not within an expected range</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError" class="type"><ReferenceError></a> : thrown when using undefined variables</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypeError" class="type"><TypeError></a> : thrown when passing arguments of the wrong type</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/URIError" class="type"><URIError></a> : thrown when a global URI handling function is misused.</li>
</ul>
</li>
<li>System errors triggered by underlying operating system constraints such
as attempting to open a file that does not exist, attempting to send data
over a closed socket, etc;</li>
<li>And User-specified errors triggered by application code.</li>
<li>Assertion Errors are a special class 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>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>
<h2>Error Propagation and Interception<span><a class="mark" href="#errors_error_propagation_and_interception" id="errors_error_propagation_and_interception">#</a></span></h2>
<!--type=misc-->
<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 Error 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="lang-js">// Throws with a ReferenceError because z is undefined
try {
const m = 1;
const n = m + z;
} catch (err) {
// Handle the error here.
}
</code></pre>
<p>Any use of the JavaScript <code>throw</code> mechanism will raise an exception that
<em>must</em> be handled using <code>try / catch</code> or the Node.js process will exit
immediately.</p>
<p>With few exceptions, <em>Synchronous</em> APIs (any blocking method that does not
accept a <code>callback</code> function, such as <a href="fs.html#fs_fs_readfilesync_file_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>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>
<pre><code class="lang-js">const fs = require('fs');
fs.readFile('a file that does not exist', (err, data) => {
if (err) {
console.error('There was an error reading the file!', err);
return;
}
// Otherwise handle the data
});
</code></pre>
</li>
<li><p>When an asynchronous method is called on an object that is an <code>EventEmitter</code>,
errors can be routed to that object's <code>'error'</code> event.</p>
<pre><code class="lang-js">const net = require('net');
const connection = net.connect('localhost');
// Adding an 'error' event handler to a stream:
connection.on('error', (err) => {
// If the connection is reset by the server, or if it can't
// connect at all, or on any sort of error encountered by
// the connection, the error will be sent here.
console.error(err);
});
connection.pipe(process.stdout);
</code></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="events.html#events_class_events_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> <code>EventEmitter</code> objects, if an <code>'error'</code> event handler is not
provided, the error will be thrown, causing the Node.js process to report an
unhandled exception and crash unless either: The <a href="domain.html"><code>domain</code></a> module is used
appropriately or a handler has been registered for the
<a href="process.html#process_event_uncaughtexception"><code>process.on('uncaughtException')</code></a> event.</p>
<pre><code class="lang-js">const EventEmitter = require('events');
const ee = new EventEmitter();
setImmediate(() => {
// This will crash the process because no 'error' event
// handler has been added.
ee.emit('error', new Error('This will crash'));
});
</code></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>
<h3>Node.js style callbacks<span><a class="mark" href="#errors_node_js_style_callbacks" id="errors_node_js_style_callbacks">#</a></span></h3>
<!--type=misc-->
<p>Most asynchronous methods exposed by the Node.js core API follow an idiomatic
pattern referred to as a "Node.js style callback". With this pattern, a
callback function is passed to the method as an argument. When the operation
either completes or an error is raised, the callback function is called with
the Error object (if any) passed as the first argument. If no error was raised,
the first argument will be passed as <code>null</code>.</p>
<pre><code class="lang-js">const fs = require('fs');
function nodeStyleCallback(err, data) {
if (err) {
console.error('There was an error', err);
return;
}
console.log(data);
}
fs.readFile('/some/file/that/does-not-exist', nodeStyleCallback);
fs.readFile('/some/file/that/does-exist', nodeStyleCallback)
</code></pre>
<p>The JavaScript <code>try / catch</code> mechanism <strong>cannot</strong> be used to intercept errors
generated by asynchronous APIs. A common mistake for beginners is to try to
use <code>throw</code> inside a Node.js style callback:</p>
<pre><code class="lang-js">// THIS WILL NOT WORK:
const fs = require('fs');
try {
fs.readFile('/some/file/that/does-not-exist', (err, data) => {
// mistaken assumption: throwing here...
if (err) {
throw err;
}
});
} catch(err) {
// This will not catch the throw!
console.log(err);
}
</code></pre>
<p>This will not work because the callback function passed to <code>fs.readFile()</code> is
called asynchronously. By the time the callback has been called, the
surrounding code (including the <code>try { } catch(err) { }</code> block will have
already exited. Throwing an error inside the callback <strong>can crash the Node.js
process</strong> in most cases. If <a href="domain.html">domains</a> are enabled, or a handler has been
registered with <code>process.on('uncaughtException')</code>, such errors can be
intercepted.</p>
<h2>Class: Error<span><a class="mark" href="#errors_class_error" id="errors_class_error">#</a></span></h2>
<!--type=class-->
<p>A generic JavaScript <code>Error</code> 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>
<h3>new Error(message)<span><a class="mark" href="#errors_new_error_message" id="errors_new_error_message">#</a></span></h3>
<div class="signature"><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>
</div><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>message.toString()</code>. 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://github.com/v8/v8/wiki/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>
<h3>Error.captureStackTrace(targetObject[, constructorOpt])<span><a class="mark" href="#errors_error_capturestacktrace_targetobject_constructoropt" id="errors_error_capturestacktrace_targetobject_constructoropt">#</a></span></h3>
<div class="signature"><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>
</div><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="lang-js">const myObject = {};
Error.captureStackTrace(myObject);
myObject.stack // similar to `new Error().stack`
</code></pre>
<p>The first line of the trace, instead of being prefixed with <code>ErrorType:
message</code>, will be the result of calling <code>targetObject.toString()</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 an end user. For instance:</p>
<pre><code class="lang-js">function MyError() {
Error.captureStackTrace(this, MyError);
}
// Without passing MyError to captureStackTrace, the MyError
// frame would show up in the .stack property. By passing
// the constructor, we omit that frame and all frames above it.
new MyError().stack
</code></pre>
<h3>Error.stackTraceLimit<span><a class="mark" href="#errors_error_stacktracelimit" id="errors_error_stacktracelimit">#</a></span></h3>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a></li>
</ul>
</div><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>error.message<span><a class="mark" href="#errors_error_message" id="errors_error_message">#</a></span></h4>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a></li>
</ul>
</div><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="lang-js">const err = new Error('The message');
console.log(err.message);
// Prints: The message
</code></pre>
<h4>error.stack<span><a class="mark" href="#errors_error_stack" id="errors_error_stack">#</a></span></h4>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a></li>
</ul>
</div><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>
<p>For example:</p>
<pre><code>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></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>It is important to note that frames are <strong>only</strong> 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 <strong>not</strong> be present in the stack
traces:</p>
<pre><code class="lang-js">const cheetahify = require('./native-binding.node');
function makeFaster() {
// cheetahify *synchronously* calls speedy.
cheetahify(function speedy() {
throw new Error('oh no!');
});
}
makeFaster(); // will throw:
// /home/gbusey/file.js:6
// throw new Error('oh no!');
// ^
// Error: oh no!
// at speedy (/home/gbusey/file.js:6:11)
// at makeFaster (/home/gbusey/file.js:5:3)
// at Object.<anonymous> (/home/gbusey/file.js:10:1)
// at Module._compile (module.js:456:26)
// at Object.Module._extensions..js (module.js:474:10)
// at Module.load (module.js:356:32)
// at Function.Module._load (module.js:312:12)
// at Function.Module.runMain (module.js:497:10)
// at startup (node.js:119:16)
// at node.js:906:3
</code></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, 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>
<p>System-level errors are generated as augmented <code>Error</code> instances, which are
detailed <a href="#errors_system_errors">here</a>.</p>
<h2>Class: RangeError<span><a class="mark" href="#errors_class_rangeerror" id="errors_class_rangeerror">#</a></span></h2>
<p>A subclass of <code>Error</code> that 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>
<p>For example:</p>
<pre><code class="lang-js">require('net').connect(-1);
// throws RangeError, port should be > 0 && < 65536
</code></pre>
<p>Node.js will generate and throw <code>RangeError</code> instances <em>immediately</em> as a form
of argument validation.</p>
<h2>Class: ReferenceError<span><a class="mark" href="#errors_class_referenceerror" id="errors_class_referenceerror">#</a></span></h2>
<p>A subclass of <code>Error</code> that 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="lang-js">doesNotExist;
// throws ReferenceError, doesNotExist is not a variable in this program.
</code></pre>
<p><code>ReferenceError</code> instances will have an <code>error.arguments</code> property whose value
is an array containing a single element: a string representing the variable
that was not defined.</p>
<pre><code class="lang-js">const assert = require('assert');
try {
doesNotExist;
} catch(err) {
assert(err.arguments[0], 'doesNotExist');
}
</code></pre>
<p>Unless an application is dynamically generating and running code,
<code>ReferenceError</code> instances should always be considered a bug in the code
or its dependencies.</p>
<h2>Class: SyntaxError<span><a class="mark" href="#errors_class_syntaxerror" id="errors_class_syntaxerror">#</a></span></h2>
<p>A subclass of <code>Error</code> that 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="lang-js">try {
require('vm').runInThisContext('binary ! isNotOk');
} catch(err) {
// err will be a SyntaxError
}
</code></pre>
<p><code>SyntaxError</code> instances are unrecoverable in the context that created them –
they may only be caught by other contexts.</p>
<h2>Class: TypeError<span><a class="mark" href="#errors_class_typeerror" id="errors_class_typeerror">#</a></span></h2>
<p>A subclass of <code>Error</code> that indicates that a provided argument is not an
allowable type. For example, passing a function to a parameter which expects a
string would be considered a TypeError.</p>
<pre><code class="lang-js">require('url').parse(() => { });
// throws TypeError, since it expected a string
</code></pre>
<p>Node.js will generate and throw <code>TypeError</code> instances <em>immediately</em> as a form
of argument validation.</p>
<h2>Exceptions vs. Errors<span><a class="mark" href="#errors_exceptions_vs_errors" id="errors_exceptions_vs_errors">#</a></span></h2>
<!--type=misc-->
<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 Error.</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>
<h2>System Errors<span><a class="mark" href="#errors_system_errors" id="errors_system_errors">#</a></span></h2>
<p>System errors are generated when exceptions occur within the program's
runtime environment. Typically, these are operational errors that occur
when an application violates an operating system constraint such as attempting
to read a file that does not exist or when the user does not have sufficient
permissions.</p>
<p>System errors are typically generated at the syscall level: an exhaustive list
of error codes and their meanings is available by running <code>man 2 intro</code> or
<code>man 3 errno</code> on most Unices; or <a href="http://man7.org/linux/man-pages/man3/errno.3.html">online</a>.</p>
<p>In Node.js, system errors are represented as augmented <code>Error</code> objects with
added properties.</p>
<h3>Class: System Error<span><a class="mark" href="#errors_class_system_error" id="errors_class_system_error">#</a></span></h3>
<h4>error.code<span><a class="mark" href="#errors_error_code" id="errors_error_code">#</a></span></h4>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a></li>
</ul>
</div><p>The <code>error.code</code> property is a string representing the error code, which is always
<code>E</code> followed by a sequence of capital letters.</p>
<h4>error.errno<span><a class="mark" href="#errors_error_errno" id="errors_error_errno">#</a></span></h4>
<div class="signature"><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#Number_type" class="type"><Number></a></li>
</ul>
</div><p>The <code>error.errno</code> property is a number or a string.
The number is a <strong>negative</strong> value which corresponds to the error code defined in
<a href="http://docs.libuv.org/en/v1.x/errors.html"><code>libuv Error handling</code></a>. See uv-errno.h header file (<code>deps/uv/include/uv-errno.h</code> in
the Node.js source tree) for details.
In case of a string, it is the same as <code>error.code</code>.</p>
<h4>error.syscall<span><a class="mark" href="#errors_error_syscall" id="errors_error_syscall">#</a></span></h4>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a></li>
</ul>
</div><p>The <code>error.syscall</code> property is a string describing the <a href="http://man7.org/linux/man-pages/man2/syscall.2.html">syscall</a> that failed.</p>
<h4>error.path<span><a class="mark" href="#errors_error_path" id="errors_error_path">#</a></span></h4>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a></li>
</ul>
</div><p>When present (e.g. in <code>fs</code> or <code>child_process</code>), the <code>error.path</code> property is a string
containing a relevant invalid pathname.</p>
<h4>error.address<span><a class="mark" href="#errors_error_address" id="errors_error_address">#</a></span></h4>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a></li>
</ul>
</div><p>When present (e.g. in <code>net</code> or <code>dgram</code>), the <code>error.address</code> property is a string
describing the address to which the connection failed.</p>
<h4>error.port<span><a class="mark" href="#errors_error_port" id="errors_error_port">#</a></span></h4>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a></li>
</ul>
</div><p>When present (e.g. in <code>net</code> or <code>dgram</code>), the <code>error.port</code> property is a number representing
the connection's port that is not available.</p>
<h3>Common System Errors<span><a class="mark" href="#errors_common_system_errors" id="errors_common_system_errors">#</a></span></h3>
<p>This list is <strong>not exhaustive</strong>, but enumerates many of the common system
errors encountered when writing a Node.js program. An exhaustive list may be
found <a href="http://man7.org/linux/man-pages/man3/errno.3.html">here</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, OS X) 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="fs.html#fs_fs_readdir_path_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="fs.html#fs_fs_unlink_path_callback"><code>fs.unlink</code></a>.</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>
<!-- [end-include:errors.md] -->
<!-- [start-include:events.md] -->
<h1>Events<span><a class="mark" href="#events_events" id="events_events">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><!--type=module-->
<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")
periodically emit named events that cause Function objects ("listeners") to be
called.</p>
<p>For instance: a <a href="net.html#net_class_net_server"><code>net.Server</code></a> object emits an event each time a peer
connects to it; a <a href="fs.html#fs_class_fs_readstream"><code>fs.ReadStream</code></a> emits an event when the file is opened;
a <a href="stream.html#stream_stream">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 will be 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><code class="lang-js">const EventEmitter = require('events');
const util = require('util');
function MyEmitter() {
EventEmitter.call(this);
}
util.inherits(MyEmitter, EventEmitter);
const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
console.log('an event occurred!');
});
myEmitter.emit('event');
</code></pre>
<p>Any object can become an <code>EventEmitter</code> through inheritance. The example above
uses the traditional Node.js style prototypical inheritance using
the <code>util.inherits()</code> method. It is, however, possible to use ES6 classes as
well:</p>
<pre><code class="lang-js">const EventEmitter = require('events');
class MyEmitter extends EventEmitter {}
const myEmitter = new MyEmitter();
myEmitter.on('event', () => {
console.log('an event occurred!');
});
myEmitter.emit('event');
</code></pre>
<h2>Passing arguments and <code>this</code> to listeners<span><a class="mark" href="#events_passing_arguments_and_this_to_listeners" id="events_passing_arguments_and_this_to_listeners">#</a></span></h2>
<p>The <code>eventEmitter.emit()</code> method allows an arbitrary set of arguments to be
passed to the listener functions. It is important to keep in mind that when an
ordinary listener function is called by the <code>EventEmitter</code>, the standard <code>this</code>
keyword is intentionally set to reference the <code>EventEmitter</code> to which the
listener is attached.</p>
<pre><code class="lang-js">const myEmitter = new MyEmitter();
myEmitter.on('event', function(a, b) {
console.log(a, b, this);
// Prints:
// a b MyEmitter {
// domain: null,
// _events: { event: [Function] },
// _eventsCount: 1,
// _maxListeners: undefined }
});
myEmitter.emit('event', 'a', 'b');
</code></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><code class="lang-js">const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
console.log(a, b, this);
// Prints: a b {}
});
myEmitter.emit('event', 'a', 'b');
</code></pre>
<h2>Asynchronous vs. Synchronous<span><a class="mark" href="#events_asynchronous_vs_synchronous" id="events_asynchronous_vs_synchronous">#</a></span></h2>
<p>The <code>EventListener</code> calls all listeners synchronously in the order in which
they were registered. This is important to ensure the proper sequencing of
events and to avoid race conditions or 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><code class="lang-js">const myEmitter = new MyEmitter();
myEmitter.on('event', (a, b) => {
setImmediate(() => {
console.log('this happens asynchronously');
});
});
myEmitter.emit('event', 'a', 'b');
</code></pre>
<h2>Handling events only once<span><a class="mark" href="#events_handling_events_only_once" id="events_handling_events_only_once">#</a></span></h2>
<p>When a listener is registered using the <code>eventEmitter.on()</code> method, that
listener will be invoked <em>every time</em> the named event is emitted.</p>
<pre><code class="lang-js">const myEmitter = new MyEmitter();
var m = 0;
myEmitter.on('event', () => {
console.log(++m);
});
myEmitter.emit('event');
// Prints: 1
myEmitter.emit('event');
// Prints: 2
</code></pre>
<p>Using the <code>eventEmitter.once()</code> method, it is possible to register a listener
that is unregistered before it is called.</p>
<pre><code class="lang-js">const myEmitter = new MyEmitter();
var m = 0;
myEmitter.once('event', () => {
console.log(++m);
});
myEmitter.emit('event');
// Prints: 1
myEmitter.emit('event');
// Ignored
</code></pre>
<h2>Error events<span><a class="mark" href="#events_error_events" id="events_error_events">#</a></span></h2>
<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 a special case
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><code class="lang-js">const myEmitter = new MyEmitter();
myEmitter.emit('error', new Error('whoops!'));
// Throws and crashes Node.js
</code></pre>
<p>To guard against crashing the Node.js process, developers can either register
a listener for the <code>process.on('uncaughtException')</code> event or use the
<a href="domain.html"><code>domain</code></a> module (<em>Note, however, that the <code>domain</code> module has been
deprecated</em>).</p>
<pre><code class="lang-js">const myEmitter = new MyEmitter();
process.on('uncaughtException', (err) => {
console.log('whoops! there was an error');
});
myEmitter.emit('error', new Error('whoops!'));
// Prints: whoops! there was an error
</code></pre>
<p>As a best practice, developers should always register listeners for the
<code>'error'</code> event:</p>
<pre><code class="lang-js">const myEmitter = new MyEmitter();
myEmitter.on('error', (err) => {
console.log('whoops! there was an error');
});
myEmitter.emit('error', new Error('whoops!'));
// Prints: whoops! there was an error
</code></pre>
<h2>Class: EventEmitter<span><a class="mark" href="#events_class_eventemitter" id="events_class_eventemitter">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.26</span>
</div><p>The <code>EventEmitter</code> class is defined and exposed by the <code>events</code> module:</p>
<pre><code class="lang-js">const EventEmitter = require('events');
</code></pre>
<p>All EventEmitters emit the event <code>'newListener'</code> when new listeners are
added and <code>'removeListener'</code> when a listener is removed.</p>
<h3>Event: 'newListener'<span><a class="mark" href="#events_event_newlistener" id="events_event_newlistener">#</a></span></h3>
<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 it's own <code>'newListener'</code> event <em>before</em>
a listener is added to it's internal array of listeners.</p>
<p>Listeners registered for the <code>'newListener'</code> event will be 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 will be inserted <em>before</em> the
listener that is in the process of being added.</p>
<pre><code class="lang-js">const myEmitter = new MyEmitter();
// Only do this once so we don't loop forever
myEmitter.once('newListener', (event, listener) => {
if (event === 'event') {
// Insert a new listener in front
myEmitter.on('event', () => {
console.log('B');
});
}
});
myEmitter.on('event', () => {
console.log('A');
});
myEmitter.emit('event');
// Prints:
// B
// A
</code></pre>
<h3>Event: 'removeListener'<span><a class="mark" href="#events_event_removelistener" id="events_event_removelistener">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.3</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 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> a listener is removed.</p>
<h3>EventEmitter.listenerCount(emitter, eventName)<span><a class="mark" href="#events_eventemitter_listenercount_emitter_eventname" id="events_eventemitter_listenercount_emitter_eventname">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.12</span>
<span>Deprecated since: v4.0.0 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated: Use <a href="#events_emitter_listenercount_event"><code>emitter.listenerCount()</code></a> instead.</pre><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><code class="lang-js">const myEmitter = new MyEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(EventEmitter.listenerCount(myEmitter, 'event'));
// Prints: 2
</code></pre>
<h3>EventEmitter.defaultMaxListeners<span><a class="mark" href="#events_eventemitter_defaultmaxlisteners" id="events_eventemitter_defaultmaxlisteners">#</a></span></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="#events_emitter_setmaxlisteners_n"><code>emitter.setMaxListeners(n)</code></a> method. To change the default
for <em>all</em> <code>EventEmitter</code> instances, the <code>EventEmitter.defaultMaxListeners</code>
property can be used.</p>
<p>Take caution when setting the <code>EventEmitter.defaultMaxListeners</code> because the
change effects <em>all</em> <code>EventEmitter</code> instances, including those created before
the change is made. However, calling <a href="#events_emitter_setmaxlisteners_n"><code>emitter.setMaxListeners(n)</code></a> still has
precedence over <code>EventEmitter.defaultMaxListeners</code>.</p>
<p>Note that 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 <code>possible EventEmitter memory leak</code> 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><code class="lang-js">emitter.setMaxListeners(emitter.getMaxListeners() + 1);
emitter.once('event', () => {
// do stuff
emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0));
});
</code></pre>
<h3>emitter.addListener(eventName, listener)<span><a class="mark" href="#events_emitter_addlistener_eventname_listener" id="events_emitter_addlistener_eventname_listener">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.26</span>
</div><p>Alias for <code>emitter.on(eventName, listener)</code>.</p>
<h3>emitter.emit(eventName[, arg1][, arg2][, ...])<span><a class="mark" href="#events_emitter_emit_eventname_arg1_arg2" id="events_emitter_emit_eventname_arg1_arg2">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.26</span>
</div><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>
<h3>emitter.getMaxListeners()<span><a class="mark" href="#events_emitter_getmaxlisteners" id="events_emitter_getmaxlisteners">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.0.0</span>
</div><p>Returns the current max listener value for the <code>EventEmitter</code> which is either
set by <a href="#events_emitter_setmaxlisteners_n"><code>emitter.setMaxListeners(n)</code></a> or defaults to
<a href="#events_eventemitter_defaultmaxlisteners"><code>EventEmitter.defaultMaxListeners</code></a>.</p>
<h3>emitter.listenerCount(eventName)<span><a class="mark" href="#events_emitter_listenercount_eventname" id="events_emitter_listenercount_eventname">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v3.2.0</span>
</div><ul>
<li><code>eventName</code> <span class="type"><Value></span> The name of the event being listened for</li>
</ul>
<p>Returns the number of listeners listening to the event named <code>eventName</code>.</p>
<h3>emitter.listeners(eventName)<span><a class="mark" href="#events_emitter_listeners_eventname" id="events_emitter_listeners_eventname">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.26</span>
</div><p>Returns a copy of the array of listeners for the event named <code>eventName</code>.</p>
<pre><code class="lang-js">server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
</code></pre>
<h3>emitter.on(eventName, listener)<span><a class="mark" href="#events_emitter_on_eventname_listener" id="events_emitter_on_eventname_listener">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.101</span>
</div><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="lang-js">server.on('connection', (stream) => {
console.log('someone connected!');
});
</code></pre>
<p>Returns a reference to the <code>EventEmitter</code> so calls can be chained.</p>
<h3>emitter.once(eventName, listener)<span><a class="mark" href="#events_emitter_once_eventname_listener" id="events_emitter_once_eventname_listener">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div><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="lang-js">server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
</code></pre>
<p>Returns a reference to the <code>EventEmitter</code> so calls can be chained.</p>
<h3>emitter.removeAllListeners([eventName])<span><a class="mark" href="#events_emitter_removealllisteners_eventname" id="events_emitter_removealllisteners_eventname">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.26</span>
</div><p>Removes all listeners, or those of the specified <code>eventName</code>.</p>
<p>Note that 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 calls can be chained.</p>
<h3>emitter.removeListener(eventName, listener)<span><a class="mark" href="#events_emitter_removelistener_eventname_listener" id="events_emitter_removelistener_eventname_listener">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.26</span>
</div><p>Removes the specified <code>listener</code> from the listener array for the event named
<code>eventName</code>.</p>
<pre><code class="lang-js">var callback = (stream) => {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
</code></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>Note that once an event has been emitted, all listeners attached to it at the
time of emitting will be 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 will behave as expected.</p>
<pre><code class="lang-js">const myEmitter = new MyEmitter();
var callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
var callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
</code></pre>
<p>Because listeners are managed using an internal array, calling this will
change the position indices of any listener registered <em>after</em> the listener
being removed. This will not impact the order in which listeners are called,
but it will means that any copies of the listener array as returned by
the <code>emitter.listeners()</code> method will need to be recreated.</p>
<p>Returns a reference to the <code>EventEmitter</code> so calls can be chained.</p>
<h3>emitter.setMaxListeners(n)<span><a class="mark" href="#events_emitter_setmaxlisteners_n" id="events_emitter_setmaxlisteners_n">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.5</span>
</div><p>By default EventEmitters 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. Obviously, not all events should be limited to just 10 listeners.
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 calls can be chained.</p>
<!-- [end-include:events.md] -->
<!-- [start-include:fs.md] -->
<h1>File System<span><a class="mark" href="#fs_file_system" id="fs_file_system">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><!--name=fs-->
<p>File I/O is provided by simple wrappers around standard POSIX functions. To
use this module do <code>require('fs')</code>. All the methods have asynchronous and
synchronous forms.</p>
<p>The asynchronous form always takes a completion callback as its last argument.
The arguments passed to the completion callback depend on the method, but the
first argument is always reserved for an exception. If the operation was
completed successfully, then the first argument will be <code>null</code> or <code>undefined</code>.</p>
<p>When using the synchronous form any exceptions are immediately thrown.
You can use try/catch to handle exceptions or allow them to bubble up.</p>
<p>Here is an example of the asynchronous version:</p>
<pre><code class="lang-js">const fs = require('fs');
fs.unlink('/tmp/hello', (err) => {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});
</code></pre>
<p>Here is the synchronous version:</p>
<pre><code class="lang-js">const fs = require('fs');
fs.unlinkSync('/tmp/hello');
console.log('successfully deleted /tmp/hello');
</code></pre>
<p>With the asynchronous methods there is no guaranteed ordering. So the
following is prone to error:</p>
<pre><code class="lang-js">fs.rename('/tmp/hello', '/tmp/world', (err) => {
if (err) throw err;
console.log('renamed complete');
});
fs.stat('/tmp/world', (err, stats) => {
if (err) throw err;
console.log(`stats: ${JSON.stringify(stats)}`);
});
</code></pre>
<p>It could be that <code>fs.stat</code> is executed before <code>fs.rename</code>.
The correct way to do this is to chain the callbacks.</p>
<pre><code class="lang-js">fs.rename('/tmp/hello', '/tmp/world', (err) => {
if (err) throw err;
fs.stat('/tmp/world', (err, stats) => {
if (err) throw err;
console.log(`stats: ${JSON.stringify(stats)}`);
});
});
</code></pre>
<p>In busy processes, the programmer is <em>strongly encouraged</em> to use the
asynchronous versions of these calls. The synchronous versions will block
the entire process until they complete--halting all connections.</p>
<p>The relative path to a filename can be used. Remember, however, that this path
will be relative to <code>process.cwd()</code>.</p>
<p>Most fs functions let you omit the callback argument. If you do, a default
callback is used that rethrows errors. To get a trace to the original call
site, set the <code>NODE_DEBUG</code> environment variable:</p>
<pre><code>$ cat script.js
function bad() {
require('fs').readFile('/');
}
bad();
$ env NODE_DEBUG=fs node script.js
fs.js:66
throw err;
^
Error: EISDIR, read
at rethrow (fs.js:61:21)
at maybeCallback (fs.js:79:42)
at Object.fs.readFile (fs.js:153:18)
at bad (/path/to/script.js:2:17)
at Object.<anonymous> (/path/to/script.js:5:1)
<etc.>
</code></pre><h2>Class: fs.FSWatcher<span><a class="mark" href="#fs_class_fs_fswatcher" id="fs_class_fs_fswatcher">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><p>Objects returned from <code>fs.watch()</code> are of this type.</p>
<h3>Event: 'change'<span><a class="mark" href="#fs_event_change" id="fs_event_change">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><ul>
<li><code>event</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> The type of fs 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> 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="#fs_fs_watch_filename_options_listener"><code>fs.watch()</code></a>.</p>
<h3>Event: 'error'<span><a class="mark" href="#fs_event_error" id="fs_event_error">#</a></span></h3>
<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.</p>
<h3>watcher.close()<span><a class="mark" href="#fs_watcher_close" id="fs_watcher_close">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><p>Stop watching for changes on the given <code>fs.FSWatcher</code>.</p>
<h2>Class: fs.ReadStream<span><a class="mark" href="#fs_class_fs_readstream" id="fs_class_fs_readstream">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.93</span>
</div><p><code>ReadStream</code> is a <a href="stream.html#stream_class_stream_readable">Readable Stream</a>.</p>
<h3>Event: 'open'<span><a class="mark" href="#fs_event_open" id="fs_event_open">#</a></span></h3>
<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"><Number></a> Integer file descriptor used by the ReadStream.</li>
</ul>
<p>Emitted when the ReadStream's file is opened.</p>
<h3>Event: 'close'<span><a class="mark" href="#fs_event_close" id="fs_event_close">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.93</span>
</div><p>Emitted when the <code>ReadStream</code>'s underlying file descriptor has been closed
using the <code>fs.close()</code> method.</p>
<h3>readStream.path<span><a class="mark" href="#fs_readstream_path" id="fs_readstream_path">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.93</span>
</div><p>The path to the file the stream is reading from.</p>
<h2>Class: fs.Stats<span><a class="mark" href="#fs_class_fs_stats" id="fs_class_fs_stats">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><p>Objects returned from <a href="#fs_fs_stat_path_callback"><code>fs.stat()</code></a>, <a href="#fs_fs_lstat_path_callback"><code>fs.lstat()</code></a> and <a href="#fs_fs_fstat_fd_callback"><code>fs.fstat()</code></a> and their
synchronous counterparts are of this type.</p>
<ul>
<li><code>stats.isFile()</code></li>
<li><code>stats.isDirectory()</code></li>
<li><code>stats.isBlockDevice()</code></li>
<li><code>stats.isCharacterDevice()</code></li>
<li><code>stats.isSymbolicLink()</code> (only valid with <a href="#fs_fs_lstat_path_callback"><code>fs.lstat()</code></a>)</li>
<li><code>stats.isFIFO()</code></li>
<li><code>stats.isSocket()</code></li>
</ul>
<p>For a regular file <a href="util.html#util_util_inspect_object_options"><code>util.inspect(stats)</code></a> would return a string very
similar to this:</p>
<pre><code class="lang-js">{
dev: 2114,
ino: 48064969,
mode: 33188,
nlink: 1,
uid: 85,
gid: 100,
rdev: 0,
size: 527,
blksize: 4096,
blocks: 8,
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></pre>
<p>Please note that <code>atime</code>, <code>mtime</code>, <code>birthtime</code>, and <code>ctime</code> are
instances of <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date"><code>Date</code></a> object and to compare the values of
these objects you should use appropriate methods. For most general
uses <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime"><code>getTime()</code></a> will return the number of
milliseconds elapsed since <em>1 January 1970 00:00:00 UTC</em> and this
integer should be sufficient for any comparison, however there are
additional methods which can be used for displaying fuzzy information.
More details can be found in the <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date">MDN JavaScript Reference</a>
page.</p>
<h3>Stat Time Values<span><a class="mark" href="#fs_stat_time_values" id="fs_stat_time_values">#</a></span></h3>
<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">mknod(2)</a>, <a href="http://man7.org/linux/man-pages/man2/utimes.2.html">utimes(2)</a>, and <a href="http://man7.org/linux/man-pages/man2/read.2.html">read(2)</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">mknod(2)</a>, <a href="http://man7.org/linux/man-pages/man2/utimes.2.html">utimes(2)</a>, and <a href="http://man7.org/linux/man-pages/man2/write.2.html">write(2)</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">chmod(2)</a>, <a href="http://man7.org/linux/man-pages/man2/chown.2.html">chown(2)</a>,
link(2), <a href="http://man7.org/linux/man-pages/man2/mknod.2.html">mknod(2)</a>, <a href="http://man7.org/linux/man-pages/man2/rename.2.html">rename(2)</a>, <a href="http://man7.org/linux/man-pages/man2/unlink.2.html">unlink(2)</a>, <a href="http://man7.org/linux/man-pages/man2/utimes.2.html">utimes(2)</a>,
read(2), and <a href="http://man7.org/linux/man-pages/man2/write.2.html">write(2)</a> system calls.</li>
<li><code>birthtime</code> "Birth Time" - Time of file creation. Set once when the
file is created. On filesystems 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>). Note that 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
utimes(2) system call.</li>
</ul>
<p>Prior to Node v0.12, the <code>ctime</code> held the <code>birthtime</code> on Windows
systems. Note that as of v0.12, <code>ctime</code> is not "creation time", and
on Unix systems, it never was.</p>
<h2>Class: fs.WriteStream<span><a class="mark" href="#fs_class_fs_writestream" id="fs_class_fs_writestream">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.93</span>
</div><p><code>WriteStream</code> is a <a href="stream.html#stream_class_stream_writable">Writable Stream</a>.</p>
<h3>Event: 'open'<span><a class="mark" href="#fs_event_open_1" id="fs_event_open_1">#</a></span></h3>
<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"><Number></a> Integer file descriptor used by the WriteStream.</li>
</ul>
<p>Emitted when the WriteStream's file is opened.</p>
<h3>Event: 'close'<span><a class="mark" href="#fs_event_close_1" id="fs_event_close_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.93</span>
</div><p>Emitted when the <code>WriteStream</code>'s underlying file descriptor has been closed
using the <code>fs.close()</code> method.</p>
<h3>writeStream.bytesWritten<span><a class="mark" href="#fs_writestream_byteswritten" id="fs_writestream_byteswritten">#</a></span></h3>
<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>
<h3>writeStream.path<span><a class="mark" href="#fs_writestream_path" id="fs_writestream_path">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.93</span>
</div><p>The path to the file the stream is writing to.</p>
<h2>fs.access(path[, mode], callback)<span><a class="mark" href="#fs_fs_access_path_mode_callback" id="fs_fs_access_path_mode_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.15</span>
</div><p>Tests a user's permissions for the file specified by <code>path</code>. <code>mode</code> is an
optional integer that specifies the accessibility checks to be performed. The
following constants define the possible values of <code>mode</code>. It is possible to
create a mask consisting of the bitwise OR of two or more values.</p>
<ul>
<li><code>fs.F_OK</code> - 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 <code>mode</code> is specified.</li>
<li><code>fs.R_OK</code> - File can be read by the calling process.</li>
<li><code>fs.W_OK</code> - File can be written by the calling process.</li>
<li><code>fs.X_OK</code> - File can be executed by the calling process. This has no effect
on Windows (will behave like <code>fs.F_OK</code>).</li>
</ul>
<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 populated. The following example checks if the file
<code>/etc/passwd</code> can be read and written by the current process.</p>
<pre><code class="lang-js">fs.access('/etc/passwd', fs.R_OK | fs.W_OK, (err) => {
console.log(err ? 'no access!' : 'can read/write');
});
</code></pre>
<p>Using <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> 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>
<p>For example:</p>
<p><strong>write (NOT RECOMMENDED)</strong></p>
<pre><code class="lang-js">fs.access('myfile', (err) => {
if (!err) {
console.error('myfile already exists');
return;
}
fs.open('myfile', 'wx', (err, fd) => {
if (err) throw err;
writeMyData(fd);
});
});
</code></pre>
<p><strong>write (RECOMMENDED)</strong></p>
<pre><code class="lang-js">fs.open('myfile', 'wx', (err, fd) => {
if (err) {
if (err.code === "EEXIST") {
console.error('myfile already exists');
return;
} else {
throw err;
}
}
writeMyData(fd);
});
</code></pre>
<p><strong>read (NOT RECOMMENDED)</strong></p>
<pre><code class="lang-js">fs.access('myfile', (err) => {
if (err) {
if (err.code === "ENOENT") {
console.error('myfile does not exist');
return;
} else {
throw err;
}
}
fs.open('myfile', 'r', (err, fd) => {
if (err) throw err;
readMyData(fd);
});
});
</code></pre>
<p><strong>read (RECOMMENDED)</strong></p>
<pre><code class="lang-js">fs.open('myfile', 'r', (err, fd) => {
if (err) {
if (err.code === "ENOENT") {
console.error('myfile does not exist');
return;
} else {
throw err;
}
}
readMyData(fd);
});
</code></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 won’t be
used directly, for example when its accessibility is a signal from another
process.</p>
<h2>fs.accessSync(path[, mode])<span><a class="mark" href="#fs_fs_accesssync_path_mode" id="fs_fs_accesssync_path_mode">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.15</span>
</div><p>Synchronous version of <a href="#fs_fs_access_path_mode_callback"><code>fs.access()</code></a>. This throws if any accessibility checks
fail, and does nothing otherwise.</p>
<h2>fs.appendFile(file, data[, options], callback)<span><a class="mark" href="#fs_fs_appendfile_file_data_options_callback" id="fs_fs_appendfile_file_data_options_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.6.7</span>
</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> filename</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="buffer.html#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> default = <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"><Number></a> default = <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> default = <code>'a'</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>
</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 buffer.</p>
<p>Example:</p>
<pre><code class="lang-js">fs.appendFile('message.txt', 'data to append', (err) => {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});
</code></pre>
<p>If <code>options</code> is a string, then it specifies the encoding. Example:</p>
<pre><code class="lang-js">fs.appendFile('message.txt', 'data to append', 'utf8', callback);
</code></pre>
<h2>fs.appendFileSync(file, data[, options])<span><a class="mark" href="#fs_fs_appendfilesync_file_data_options" id="fs_fs_appendfilesync_file_data_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.6.7</span>
</div><p>The synchronous version of <a href="fs.html#fs_fs_appendfile_file_data_options_callback"><code>fs.appendFile()</code></a>. Returns <code>undefined</code>.</p>
<h2>fs.chmod(path, mode, callback)<span><a class="mark" href="#fs_fs_chmod_path_mode_callback" id="fs_fs_chmod_path_mode_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.30</span>
</div><p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/chmod.2.html">chmod(2)</a>. No arguments other than a possible exception are given
to the completion callback.</p>
<h2>fs.chmodSync(path, mode)<span><a class="mark" href="#fs_fs_chmodsync_path_mode" id="fs_fs_chmodsync_path_mode">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.6.7</span>
</div><p>Synchronous <a href="http://man7.org/linux/man-pages/man2/chmod.2.html">chmod(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.chown(path, uid, gid, callback)<span><a class="mark" href="#fs_fs_chown_path_uid_gid_callback" id="fs_fs_chown_path_uid_gid_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.97</span>
</div><p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/chown.2.html">chown(2)</a>. No arguments other than a possible exception are given
to the completion callback.</p>
<h2>fs.chownSync(path, uid, gid)<span><a class="mark" href="#fs_fs_chownsync_path_uid_gid" id="fs_fs_chownsync_path_uid_gid">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.97</span>
</div><p>Synchronous <a href="http://man7.org/linux/man-pages/man2/chown.2.html">chown(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.close(fd, callback)<span><a class="mark" href="#fs_fs_close_fd_callback" id="fs_fs_close_fd_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.2</span>
</div><p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/close.2.html">close(2)</a>. No arguments other than a possible exception are given
to the completion callback.</p>
<h2>fs.closeSync(fd)<span><a class="mark" href="#fs_fs_closesync_fd" id="fs_fs_closesync_fd">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><p>Synchronous <a href="http://man7.org/linux/man-pages/man2/close.2.html">close(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.createReadStream(path[, options])<span><a class="mark" href="#fs_fs_createreadstream_path_options" id="fs_fs_createreadstream_path_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.31</span>
</div><p>Returns a new <a href="#fs_class_fs_readstream"><code>ReadStream</code></a> object. (See <a href="stream.html#stream_class_stream_readable">Readable Stream</a>).</p>
<p>Be aware that, unlike the default value set for <code>highWaterMark</code> on a
readable stream (16 kb), the stream returned by this method has a
default value of 64 kb for the same parameter.</p>
<p><code>options</code> is an object or string with the following defaults:</p>
<pre><code class="lang-js">{
flags: 'r',
encoding: null,
fd: null,
mode: 0o666,
autoClose: true
}
</code></pre>
<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. 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="buffer.html#buffer_buffer"><code>Buffer</code></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.
Note that <code>fd</code> should be blocking; non-blocking <code>fd</code>s should be passed to
<a href="net.html#net_class_net_socket"><code>net.Socket</code></a>.</p>
<p>If <code>autoClose</code> is false, then the file descriptor won't be closed, even if
there's an error. It is your 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="lang-js">fs.createReadStream('sample.txt', {start: 90, end: 99});
</code></pre>
<p>If <code>options</code> is a string, then it specifies the encoding.</p>
<h2>fs.createWriteStream(path[, options])<span><a class="mark" href="#fs_fs_createwritestream_path_options" id="fs_fs_createwritestream_path_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.31</span>
</div><p>Returns a new <a href="#fs_class_fs_writestream"><code>WriteStream</code></a> object. (See <a href="stream.html#stream_class_stream_writable">Writable Stream</a>).</p>
<p><code>options</code> is an object or string with the following defaults:</p>
<pre><code class="lang-js">{
flags: 'w',
defaultEncoding: 'utf8',
fd: null,
mode: 0o666
}
</code></pre>
<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. Modifying a file rather
than replacing it may require a <code>flags</code> mode of <code>r+</code> rather than the
default mode <code>w</code>. The <code>defaultEncoding</code> can be any one of those accepted by <a href="buffer.html#buffer_buffer"><code>Buffer</code></a>.</p>
<p>Like <a href="#fs_class_fs_readstream"><code>ReadStream</code></a>, if <code>fd</code> is specified, <code>WriteStream</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. Note that <code>fd</code> should be blocking; non-blocking
<code>fd</code>s should be passed to <a href="net.html#net_class_net_socket"><code>net.Socket</code></a>.</p>
<p>If <code>options</code> is a string, then it specifies the encoding.</p>
<h2>fs.exists(path, callback)<span><a class="mark" href="#fs_fs_exists_path_callback" id="fs_fs_exists_path_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.2</span>
<span>Deprecated since: v1.0.0 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated: Use <a href="#fs_fs_stat_path_callback"><code>fs.stat()</code></a> or <a href="#fs_fs_access_path_mode_callback"><code>fs.access()</code></a> instead.</pre><p>Test whether or not the given path exists by checking with the file system.
Then call the <code>callback</code> argument with either true or false. Example:</p>
<pre><code class="lang-js">fs.exists('/etc/passwd', (exists) => {
console.log(exists ? 'it\'s there' : 'no passwd!');
});
</code></pre>
<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>For example:</p>
<p><strong>write (NOT RECOMMENDED)</strong></p>
<pre><code class="lang-js">fs.exists('myfile', (exists) => {
if (exists) {
console.error('myfile already exists');
} else {
fs.open('myfile', 'wx', (err, fd) => {
if (err) throw err;
writeMyData(fd);
});
}
});
</code></pre>
<p><strong>write (RECOMMENDED)</strong></p>
<pre><code class="lang-js">fs.open('myfile', 'wx', (err, fd) => {
if (err) {
if (err.code === "EEXIST") {
console.error('myfile already exists');
return;
} else {
throw err;
}
}
writeMyData(fd);
});
</code></pre>
<p><strong>read (NOT RECOMMENDED)</strong></p>
<pre><code class="lang-js">fs.exists('myfile', (exists) => {
if (exists) {
fs.open('myfile', 'r', (err, fd) => {
readMyData(fd);
});
} else {
console.error('myfile does not exist');
}
});
</code></pre>
<p><strong>read (RECOMMENDED)</strong></p>
<pre><code class="lang-js">fs.open('myfile', 'r', (err, fd) => {
if (err) {
if (err.code === "ENOENT") {
console.error('myfile does not exist');
return;
} else {
throw err;
}
} else {
readMyData(fd);
}
});
</code></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>
<h2>fs.existsSync(path)<span><a class="mark" href="#fs_fs_existssync_path" id="fs_fs_existssync_path">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
<span>Deprecated since: v1.0.0 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated: Use <a href="#fs_fs_statsync_path"><code>fs.statSync()</code></a> or <a href="#fs_fs_accesssync_path_mode"><code>fs.accessSync()</code></a> instead.</pre><p>Synchronous version of <a href="fs.html#fs_fs_exists_path_callback"><code>fs.exists()</code></a>.
Returns <code>true</code> if the file exists, <code>false</code> otherwise.</p>
<h2>fs.fchmod(fd, mode, callback)<span><a class="mark" href="#fs_fs_fchmod_fd_mode_callback" id="fs_fs_fchmod_fd_mode_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.4.7</span>
</div><p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/fchmod.2.html">fchmod(2)</a>. No arguments other than a possible exception
are given to the completion callback.</p>
<h2>fs.fchmodSync(fd, mode)<span><a class="mark" href="#fs_fs_fchmodsync_fd_mode" id="fs_fs_fchmodsync_fd_mode">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.4.7</span>
</div><p>Synchronous <a href="http://man7.org/linux/man-pages/man2/fchmod.2.html">fchmod(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.fchown(fd, uid, gid, callback)<span><a class="mark" href="#fs_fs_fchown_fd_uid_gid_callback" id="fs_fs_fchown_fd_uid_gid_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.4.7</span>
</div><p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/fchown.2.html">fchown(2)</a>. No arguments other than a possible exception are given
to the completion callback.</p>
<h2>fs.fchownSync(fd, uid, gid)<span><a class="mark" href="#fs_fs_fchownsync_fd_uid_gid" id="fs_fs_fchownsync_fd_uid_gid">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.4.7</span>
</div><p>Synchronous <a href="http://man7.org/linux/man-pages/man2/fchown.2.html">fchown(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.fdatasync(fd, callback)<span><a class="mark" href="#fs_fs_fdatasync_fd_callback" id="fs_fs_fdatasync_fd_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.96</span>
</div><p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/fdatasync.2.html">fdatasync(2)</a>. No arguments other than a possible exception are
given to the completion callback.</p>
<h2>fs.fdatasyncSync(fd)<span><a class="mark" href="#fs_fs_fdatasyncsync_fd" id="fs_fs_fdatasyncsync_fd">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.96</span>
</div><p>Synchronous <a href="http://man7.org/linux/man-pages/man2/fdatasync.2.html">fdatasync(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.fstat(fd, callback)<span><a class="mark" href="#fs_fs_fstat_fd_callback" id="fs_fs_fstat_fd_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.95</span>
</div><p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/fstat.2.html">fstat(2)</a>. The callback gets two arguments <code>(err, stats)</code> where
<code>stats</code> is a <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object. <code>fstat()</code> is identical to <a href="fs.html#fs_fs_stat_path_callback"><code>stat()</code></a>,
except that the file to be stat-ed is specified by the file descriptor <code>fd</code>.</p>
<h2>fs.fstatSync(fd)<span><a class="mark" href="#fs_fs_fstatsync_fd" id="fs_fs_fstatsync_fd">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.95</span>
</div><p>Synchronous <a href="http://man7.org/linux/man-pages/man2/fstat.2.html">fstat(2)</a>. Returns an instance of <code>fs.Stats</code>.</p>
<h2>fs.fsync(fd, callback)<span><a class="mark" href="#fs_fs_fsync_fd_callback" id="fs_fs_fsync_fd_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.96</span>
</div><p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/fsync.2.html">fsync(2)</a>. No arguments other than a possible exception are given
to the completion callback.</p>
<h2>fs.fsyncSync(fd)<span><a class="mark" href="#fs_fs_fsyncsync_fd" id="fs_fs_fsyncsync_fd">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.96</span>
</div><p>Synchronous <a href="http://man7.org/linux/man-pages/man2/fsync.2.html">fsync(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.ftruncate(fd, len, callback)<span><a class="mark" href="#fs_fs_ftruncate_fd_len_callback" id="fs_fs_ftruncate_fd_len_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.8.6</span>
</div><p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/ftruncate.2.html">ftruncate(2)</a>. No arguments other than a possible exception are
given to the completion callback.</p>
<h2>fs.ftruncateSync(fd, len)<span><a class="mark" href="#fs_fs_ftruncatesync_fd_len" id="fs_fs_ftruncatesync_fd_len">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.8.6</span>
</div><p>Synchronous <a href="http://man7.org/linux/man-pages/man2/ftruncate.2.html">ftruncate(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.futimes(fd, atime, mtime, callback)<span><a class="mark" href="#fs_fs_futimes_fd_atime_mtime_callback" id="fs_fs_futimes_fd_atime_mtime_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.4.2</span>
</div><p>Change the file timestamps of a file referenced by the supplied file
descriptor.</p>
<h2>fs.futimesSync(fd, atime, mtime)<span><a class="mark" href="#fs_fs_futimessync_fd_atime_mtime" id="fs_fs_futimessync_fd_atime_mtime">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.4.2</span>
</div><p>Synchronous version of <a href="#fs_fs_futimes_fd_atime_mtime_callback"><code>fs.futimes()</code></a>. Returns <code>undefined</code>.</p>
<h2>fs.lchmod(path, mode, callback)<span><a class="mark" href="#fs_fs_lchmod_path_mode_callback" id="fs_fs_lchmod_path_mode_callback">#</a></span></h2>
<div class="api_metadata">
<span>Deprecated since: v0.4.7 </span>
</div><p>Asynchronous <a href="https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2">lchmod(2)</a>. No arguments other than a possible exception
are given to the completion callback.</p>
<p>Only available on Mac OS X.</p>
<h2>fs.lchmodSync(path, mode)<span><a class="mark" href="#fs_fs_lchmodsync_path_mode" id="fs_fs_lchmodsync_path_mode">#</a></span></h2>
<div class="api_metadata">
<span>Deprecated since: v0.4.7 </span>
</div><p>Synchronous <a href="https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2">lchmod(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.lchown(path, uid, gid, callback)<span><a class="mark" href="#fs_fs_lchown_path_uid_gid_callback" id="fs_fs_lchown_path_uid_gid_callback">#</a></span></h2>
<div class="api_metadata">
<span>Deprecated since: v0.4.7 </span>
</div><p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/lchown.2.html">lchown(2)</a>. No arguments other than a possible exception are given
to the completion callback.</p>
<h2>fs.lchownSync(path, uid, gid)<span><a class="mark" href="#fs_fs_lchownsync_path_uid_gid" id="fs_fs_lchownsync_path_uid_gid">#</a></span></h2>
<div class="api_metadata">
<span>Deprecated since: v0.4.7 </span>
</div><p>Synchronous <a href="http://man7.org/linux/man-pages/man2/lchown.2.html">lchown(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.link(srcpath, dstpath, callback)<span><a class="mark" href="#fs_fs_link_srcpath_dstpath_callback" id="fs_fs_link_srcpath_dstpath_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.31</span>
</div><p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/link.2.html">link(2)</a>. No arguments other than a possible exception are given to
the completion callback.</p>
<h2>fs.linkSync(srcpath, dstpath)<span><a class="mark" href="#fs_fs_linksync_srcpath_dstpath" id="fs_fs_linksync_srcpath_dstpath">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.31</span>
</div><p>Synchronous <a href="http://man7.org/linux/man-pages/man2/link.2.html">link(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.lstat(path, callback)<span><a class="mark" href="#fs_fs_lstat_path_callback" id="fs_fs_lstat_path_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.30</span>
</div><p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/lstat.2.html">lstat(2)</a>. The callback gets two arguments <code>(err, stats)</code> where
<code>stats</code> is a <a href="#fs_class_fs_stats"><code>fs.Stats</code></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>
<h2>fs.lstatSync(path)<span><a class="mark" href="#fs_fs_lstatsync_path" id="fs_fs_lstatsync_path">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.30</span>
</div><p>Synchronous <a href="http://man7.org/linux/man-pages/man2/lstat.2.html">lstat(2)</a>. Returns an instance of <code>fs.Stats</code>.</p>
<h2>fs.mkdir(path[, mode], callback)<span><a class="mark" href="#fs_fs_mkdir_path_mode_callback" id="fs_fs_mkdir_path_mode_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.8</span>
</div><p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/mkdir.2.html">mkdir(2)</a>. No arguments other than a possible exception are given
to the completion callback. <code>mode</code> defaults to <code>0o777</code>.</p>
<h2>fs.mkdirSync(path[, mode])<span><a class="mark" href="#fs_fs_mkdirsync_path_mode" id="fs_fs_mkdirsync_path_mode">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><p>Synchronous <a href="http://man7.org/linux/man-pages/man2/mkdir.2.html">mkdir(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.mkdtemp(prefix, callback)<span><a class="mark" href="#fs_fs_mkdtemp_prefix_callback" id="fs_fs_mkdtemp_prefix_callback">#</a></span></h2>
<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.</p>
<p>The created folder path is passed as a string to the callback's second
parameter.</p>
<p>Example:</p>
<pre><code class="lang-js">fs.mkdtemp('/tmp/foo-', (err, folder) => {
console.log(folder);
// Prints: /tmp/foo-itXde2
});
</code></pre>
<h2>fs.mkdtempSync(template)<span><a class="mark" href="#fs_fs_mkdtempsync_template" id="fs_fs_mkdtempsync_template">#</a></span></h2>
<p>The synchronous version of [<code>fs.mkdtemp()</code>][]. Returns the created
folder path.</p>
<h2>fs.open(path, flags[, mode], callback)<span><a class="mark" href="#fs_fs_open_path_flags_mode_callback" id="fs_fs_open_path_flags_mode_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.2</span>
</div><p>Asynchronous file open. See <a href="http://man7.org/linux/man-pages/man2/open.2.html">open(2)</a>. <code>flags</code> can be:</p>
<ul>
<li><p><code>'r'</code> - Open file for reading.
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 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 you to
skip the potentially stale local cache. It has a very real impact on I/O
performance so don't use this flag unless you need it.</p>
<p>Note that this doesn't turn <code>fs.open()</code> into a synchronous blocking call.
If that's what you want then you should be using <code>fs.openSync()</code></p>
</li>
<li><p><code>'rs+'</code> - Open file for reading and writing, telling the OS to open it
synchronously. See notes for <code>'rs'</code> about using this with caution.</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 <code>path</code> 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 <code>path</code> exists.</p>
</li>
<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 <code>path</code> 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 <code>path</code> exists.</p>
</li>
</ul>
<p><code>mode</code> sets the file mode (permission and sticky bits), but only if the file was
created. It defaults to <code>0666</code>, readable and writable.</p>
<p>The callback gets two arguments <code>(err, fd)</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">open(2)</a>) ensures that <code>path</code> is newly
created. On POSIX systems, <code>path</code> is considered to exist even if it is a symlink
to a non-existent file. The exclusive flag may or may not work with network file
systems.</p>
<p><code>flags</code> can also be a number as documented by <a href="http://man7.org/linux/man-pages/man2/open.2.html">open(2)</a>; commonly used constants
are available from <code>require('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 CreateFileW.</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>
<h2>fs.openSync(path, flags[, mode])<span><a class="mark" href="#fs_fs_opensync_path_flags_mode" id="fs_fs_opensync_path_flags_mode">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><p>Synchronous version of <a href="#fs_fs_open_path_flags_mode_callback"><code>fs.open()</code></a>. Returns an integer representing the file
descriptor.</p>
<h2>fs.read(fd, buffer, offset, length, position, callback)<span><a class="mark" href="#fs_fs_read_fd_buffer_offset_length_position_callback" id="fs_fs_read_fd_buffer_offset_length_position_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.2</span>
</div><p>Read data from the file specified by <code>fd</code>.</p>
<p><code>buffer</code> is the buffer that the data will be written to.</p>
<p><code>offset</code> is the offset in the buffer to start writing at.</p>
<p><code>length</code> is an integer specifying the number of bytes to read.</p>
<p><code>position</code> is an integer specifying where to begin reading from in the file.
If <code>position</code> is <code>null</code>, data will be read from the current file position.</p>
<p>The callback is given the three arguments, <code>(err, bytesRead, buffer)</code>.</p>
<h2>fs.readdir(path, callback)<span><a class="mark" href="#fs_fs_readdir_path_callback" id="fs_fs_readdir_path_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.8</span>
</div><p>Asynchronous <a href="http://man7.org/linux/man-pages/man3/readdir.3.html">readdir(3)</a>. 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>
<h2>fs.readdirSync(path)<span><a class="mark" href="#fs_fs_readdirsync_path" id="fs_fs_readdirsync_path">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><p>Synchronous <a href="http://man7.org/linux/man-pages/man3/readdir.3.html">readdir(3)</a>. Returns an array of filenames excluding <code>'.'</code> and
<code>'..'</code>.</p>
<h2>fs.readFile(file[, options], callback)<span><a class="mark" href="#fs_fs_readfile_file_options_callback" id="fs_fs_readfile_file_options_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.29</span>
</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> filename</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> default = <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> default = <code>'r'</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>
</ul>
<p>Asynchronously reads the entire contents of a file. Example:</p>
<pre><code class="lang-js">fs.readFile('/etc/passwd', (err, data) => {
if (err) throw err;
console.log(data);
});
</code></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. Example:</p>
<pre><code class="lang-js">fs.readFile('/etc/passwd', 'utf8', callback);
</code></pre>
<h2>fs.readFileSync(file[, options])<span><a class="mark" href="#fs_fs_readfilesync_file_options" id="fs_fs_readfilesync_file_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.8</span>
</div><p>Synchronous version of <a href="#fs_fs_readfile_file_options_callback"><code>fs.readFile</code></a>. Returns the contents of the <code>file</code>.</p>
<p>If the <code>encoding</code> option is specified then this function returns a
string. Otherwise it returns a buffer.</p>
<h2>fs.readlink(path, callback)<span><a class="mark" href="#fs_fs_readlink_path_callback" id="fs_fs_readlink_path_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.31</span>
</div><p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/readlink.2.html">readlink(2)</a>. The callback gets two arguments <code>(err,
linkString)</code>.</p>
<h2>fs.readlinkSync(path)<span><a class="mark" href="#fs_fs_readlinksync_path" id="fs_fs_readlinksync_path">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.31</span>
</div><p>Synchronous <a href="http://man7.org/linux/man-pages/man2/readlink.2.html">readlink(2)</a>. Returns the symbolic link's string value.</p>
<h2>fs.realpath(path[, cache], callback)<span><a class="mark" href="#fs_fs_realpath_path_cache_callback" id="fs_fs_realpath_path_cache_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.31</span>
</div><p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/realpath.2.html">realpath(2)</a>. The <code>callback</code> gets two arguments <code>(err,
resolvedPath)</code>. May use <code>process.cwd</code> to resolve relative paths. <code>cache</code> is an
object literal of mapped paths that can be used to force a specific path
resolution or avoid additional <code>fs.stat</code> calls for known real paths.</p>
<p>Example:</p>
<pre><code class="lang-js">var cache = {'/etc':'/private/etc'};
fs.realpath('/etc/passwd', cache, (err, resolvedPath) => {
if (err) throw err;
console.log(resolvedPath);
});
</code></pre>
<h2>fs.readSync(fd, buffer, offset, length, position)<span><a class="mark" href="#fs_fs_readsync_fd_buffer_offset_length_position" id="fs_fs_readsync_fd_buffer_offset_length_position">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><p>Synchronous version of <a href="#fs_fs_read_fd_buffer_offset_length_position_callback"><code>fs.read()</code></a>. Returns the number of <code>bytesRead</code>.</p>
<h2>fs.realpathSync(path[, cache])<span><a class="mark" href="#fs_fs_realpathsync_path_cache" id="fs_fs_realpathsync_path_cache">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.31</span>
</div><p>Synchronous <a href="http://man7.org/linux/man-pages/man2/realpath.2.html">realpath(2)</a>. Returns the resolved path. <code>cache</code> is an
object literal of mapped paths that can be used to force a specific path
resolution or avoid additional <code>fs.stat</code> calls for known real paths.</p>
<h2>fs.rename(oldPath, newPath, callback)<span><a class="mark" href="#fs_fs_rename_oldpath_newpath_callback" id="fs_fs_rename_oldpath_newpath_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.2</span>
</div><p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/rename.2.html">rename(2)</a>. No arguments other than a possible exception are given
to the completion callback.</p>
<h2>fs.renameSync(oldPath, newPath)<span><a class="mark" href="#fs_fs_renamesync_oldpath_newpath" id="fs_fs_renamesync_oldpath_newpath">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><p>Synchronous <a href="http://man7.org/linux/man-pages/man2/rename.2.html">rename(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.rmdir(path, callback)<span><a class="mark" href="#fs_fs_rmdir_path_callback" id="fs_fs_rmdir_path_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.2</span>
</div><p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/rmdir.2.html">rmdir(2)</a>. No arguments other than a possible exception are given
to the completion callback.</p>
<h2>fs.rmdirSync(path)<span><a class="mark" href="#fs_fs_rmdirsync_path" id="fs_fs_rmdirsync_path">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><p>Synchronous <a href="http://man7.org/linux/man-pages/man2/rmdir.2.html">rmdir(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.stat(path, callback)<span><a class="mark" href="#fs_fs_stat_path_callback" id="fs_fs_stat_path_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.2</span>
</div><p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/stat.2.html">stat(2)</a>. The callback gets two arguments <code>(err, stats)</code> where
<code>stats</code> is a <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> object. See the <a href="#fs_class_fs_stats"><code>fs.Stats</code></a> section for more
information.</p>
<h2>fs.statSync(path)<span><a class="mark" href="#fs_fs_statsync_path" id="fs_fs_statsync_path">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><p>Synchronous <a href="http://man7.org/linux/man-pages/man2/stat.2.html">stat(2)</a>. Returns an instance of <a href="#fs_class_fs_stats"><code>fs.Stats</code></a>.</p>
<h2>fs.symlink(target, path[, type], callback)<span><a class="mark" href="#fs_fs_symlink_target_path_type_callback" id="fs_fs_symlink_target_path_type_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.31</span>
</div><p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/symlink.2.html">symlink(2)</a>. No arguments other than a possible exception are given
to the completion callback.
The <code>type</code> argument can be set to <code>'dir'</code>, <code>'file'</code>, or <code>'junction'</code> (default
is <code>'file'</code>) and is only available on Windows (ignored on other platforms).
Note that 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.</p>
<p>Here is an example below:</p>
<pre><code class="lang-js">fs.symlink('./foo', './new-port');
</code></pre>
<p>It creates a symbolic link named "new-port" that points to "foo".</p>
<h2>fs.symlinkSync(target, path[, type])<span><a class="mark" href="#fs_fs_symlinksync_target_path_type" id="fs_fs_symlinksync_target_path_type">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.31</span>
</div><p>Synchronous <a href="http://man7.org/linux/man-pages/man2/symlink.2.html">symlink(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.truncate(path, len, callback)<span><a class="mark" href="#fs_fs_truncate_path_len_callback" id="fs_fs_truncate_path_len_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.8.6</span>
</div><p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/truncate.2.html">truncate(2)</a>. 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>
<h2>fs.truncateSync(path, len)<span><a class="mark" href="#fs_fs_truncatesync_path_len" id="fs_fs_truncatesync_path_len">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.8.6</span>
</div><p>Synchronous <a href="http://man7.org/linux/man-pages/man2/truncate.2.html">truncate(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.unlink(path, callback)<span><a class="mark" href="#fs_fs_unlink_path_callback" id="fs_fs_unlink_path_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.2</span>
</div><p>Asynchronous <a href="http://man7.org/linux/man-pages/man2/unlink.2.html">unlink(2)</a>. No arguments other than a possible exception are given
to the completion callback.</p>
<h2>fs.unlinkSync(path)<span><a class="mark" href="#fs_fs_unlinksync_path" id="fs_fs_unlinksync_path">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><p>Synchronous <a href="http://man7.org/linux/man-pages/man2/unlink.2.html">unlink(2)</a>. Returns <code>undefined</code>.</p>
<h2>fs.unwatchFile(filename[, listener])<span><a class="mark" href="#fs_fs_unwatchfile_filename_listener" id="fs_fs_unwatchfile_filename_listener">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.31</span>
</div><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 and you
have effectively stopped watching <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><em>Note: <a href="#fs_fs_watch_filename_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.</em></p>
<h2>fs.utimes(path, atime, mtime, callback)<span><a class="mark" href="#fs_fs_utimes_path_atime_mtime_callback" id="fs_fs_utimes_path_atime_mtime_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.4.2</span>
</div><p>Change file timestamps of the file referenced by the supplied path.</p>
<p>Note: the arguments <code>atime</code> and <code>mtime</code> of the following related functions does
follow the below rules:</p>
<ul>
<li>If the value is a numberable string like <code>'123456789'</code>, the value would get
converted to corresponding number.</li>
<li>If the value is <code>NaN</code> or <code>Infinity</code>, the value would get converted to
<code>Date.now()</code>.</li>
</ul>
<h2>fs.utimesSync(path, atime, mtime)<span><a class="mark" href="#fs_fs_utimessync_path_atime_mtime" id="fs_fs_utimessync_path_atime_mtime">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.4.2</span>
</div><p>Synchronous version of <a href="#fs_fs_futimes_fd_atime_mtime_callback"><code>fs.utimes()</code></a>. Returns <code>undefined</code>.</p>
<h2>fs.watch(filename[, options][, listener])<span><a class="mark" href="#fs_fs_watch_filename_options_listener" id="fs_fs_watch_filename_options_listener">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.10</span>
</div><p>Watch for changes on <code>filename</code>, where <code>filename</code> is either a file or a
directory. The returned object is a <a href="#fs_class_fs_fswatcher"><code>fs.FSWatcher</code></a>.</p>
<p>The second argument is optional. The <code>options</code> if provided should be an object.
The supported boolean members are <code>persistent</code> and <code>recursive</code>. <code>persistent</code>
indicates whether the process should continue to run as long as files are being
watched. <code>recursive</code> 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="#fs_caveats">Caveats</a>).</p>
<p>The default is <code>{ persistent: true, recursive: false }</code>.</p>
<p>The listener callback gets two arguments <code>(event, filename)</code>. <code>event</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>
<h3>Caveats<span><a class="mark" href="#fs_caveats" id="fs_caveats">#</a></span></h3>
<!--type=misc-->
<p>The <code>fs.watch</code> API is not 100% consistent across platforms, and is
unavailable in some situations.</p>
<p>The recursive option is only supported on OS X and Windows.</p>
<h4>Availability<span><a class="mark" href="#fs_availability" id="fs_availability">#</a></span></h4>
<!--type=misc-->
<p>This feature depends on the underlying operating system providing a way
to be notified of filesystem changes.</p>
<ul>
<li>On Linux systems, this uses <code>inotify</code>.</li>
<li>On BSD systems, this uses <code>kqueue</code>.</li>
<li>On OS X, this uses <code>kqueue</code> for files and 'FSEvents' for directories.</li>
<li>On SunOS systems (including Solaris and SmartOS), this uses <code>event ports</code>.</li>
<li>On Windows systems, this feature depends on <code>ReadDirectoryChangesW</code>.</li>
<li>On Aix systems, this feature depends on <code>AHAFS</code>, which must be enabled.</li>
</ul>
<p>If the underlying functionality is not available for some reason, then
<code>fs.watch</code> will not be able to function. 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, Docker, etc.</p>
<p>You can still use <code>fs.watchFile</code>, which uses stat polling, but it is slower and
less reliable.</p>
<h4>Inodes<span><a class="mark" href="#fs_inodes" id="fs_inodes">#</a></span></h4>
<!--type=misc-->
<p>On Linux and OS X systems, <code>fs.watch()</code> resolves the path to an <a href="http://www.linux.org/threads/intro-to-inodes.4130">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>
<h4>Filename Argument<span><a class="mark" href="#fs_filename_argument" id="fs_filename_argument">#</a></span></h4>
<!--type=misc-->
<p>Providing <code>filename</code> argument in the callback is only supported on Linux and
Windows. 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 null.</p>
<pre><code class="lang-js">fs.watch('somedir', (event, filename) => {
console.log(`event is: ${event}`);
if (filename) {
console.log(`filename provided: ${filename}`);
} else {
console.log('filename not provided');
}
});
</code></pre>
<h2>fs.watchFile(filename[, options], listener)<span><a class="mark" href="#fs_fs_watchfile_filename_options_listener" id="fs_fs_watchfile_filename_options_listener">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.31</span>
</div><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. The default is
<code>{ persistent: true, interval: 5007 }</code>.</p>
<p>The <code>listener</code> gets two arguments the current stat object and the previous
stat object:</p>
<pre><code class="lang-js">fs.watchFile('message.text', (curr, prev) => {
console.log(`the current mtime is: ${curr.mtime}`);
console.log(`the previous mtime was: ${prev.mtime}`);
});
</code></pre>
<p>These stat objects are instances of <code>fs.Stat</code>.</p>
<p>If you want to be notified when the file was modified, not just accessed,
you need to compare <code>curr.mtime</code> and <code>prev.mtime</code>.</p>
<p><em>Note: 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). In Windows, <code>blksize</code> and <code>blocks</code> fields will be <code>undefined</code>, instead
of zero. 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.</em></p>
<p><em>Note: <a href="#fs_fs_watch_filename_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.</em></p>
<h2>fs.write(fd, buffer, offset, length[, position], callback)<span><a class="mark" href="#fs_fs_write_fd_buffer_offset_length_position_callback" id="fs_fs_write_fd_buffer_offset_length_position_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.2</span>
</div><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">pwrite(2)</a>.</p>
<p>The callback will be given three arguments <code>(err, written, buffer)</code> where
<code>written</code> specifies how many <em>bytes</em> were written from <code>buffer</code>.</p>
<p>Note that it is unsafe to use <code>fs.write</code> multiple times on the same file
without waiting for the callback. For this scenario,
<code>fs.createWriteStream</code> is strongly 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>
<h2>fs.write(fd, data[, position[, encoding]], callback)<span><a class="mark" href="#fs_fs_write_fd_data_position_encoding_callback" id="fs_fs_write_fd_data_position_encoding_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.5</span>
</div><p>Write <code>data</code> to the file specified by <code>fd</code>. If <code>data</code> is not a Buffer instance
then the value will be coerced to a string.</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">pwrite(2)</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. Note that
bytes written is not the same as string characters. See <a href="buffer.html#buffer_class_method_buffer_bytelength_string_encoding"><code>Buffer.byteLength</code></a>.</p>
<p>Unlike when writing <code>buffer</code>, the entire string must be written. No substring
may be specified. This is because the byte offset of the resulting data may not
be the same as the string offset.</p>
<p>Note that it is unsafe to use <code>fs.write</code> multiple times on the same file
without waiting for the callback. For this scenario,
<code>fs.createWriteStream</code> is strongly 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>
<h2>fs.writeFile(file, data[, options], callback)<span><a class="mark" href="#fs_fs_writefile_file_data_options_callback" id="fs_fs_writefile_file_data_options_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.29</span>
</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> filename</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="buffer.html#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> default = <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"><Number></a> default = <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> default = <code>'w'</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>
</ul>
<p>Asynchronously writes data to a file, replacing the file if it already exists.
<code>data</code> can be a string or a buffer.</p>
<p>The <code>encoding</code> option is ignored if <code>data</code> is a buffer. It defaults
to <code>'utf8'</code>.</p>
<p>Example:</p>
<pre><code class="lang-js">fs.writeFile('message.txt', 'Hello Node.js', (err) => {
if (err) throw err;
console.log('It\'s saved!');
});
</code></pre>
<p>If <code>options</code> is a string, then it specifies the encoding. Example:</p>
<pre><code class="lang-js">fs.writeFile('message.txt', 'Hello Node.js', 'utf8', callback);
</code></pre>
<p>Note that it is unsafe to use <code>fs.writeFile</code> multiple times on the same file
without waiting for the callback. For this scenario,
<code>fs.createWriteStream</code> is strongly recommended.</p>
<h2>fs.writeFileSync(file, data[, options])<span><a class="mark" href="#fs_fs_writefilesync_file_data_options" id="fs_fs_writefilesync_file_data_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.29</span>
</div><p>The synchronous version of <a href="#fs_fs_writefile_file_data_options_callback"><code>fs.writeFile()</code></a>. Returns <code>undefined</code>.</p>
<h2>fs.writeSync(fd, buffer, offset, length[, position])<span><a class="mark" href="#fs_fs_writesync_fd_buffer_offset_length_position" id="fs_fs_writesync_fd_buffer_offset_length_position">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.21</span>
</div><h2>fs.writeSync(fd, data[, position[, encoding]])<span><a class="mark" href="#fs_fs_writesync_fd_data_position_encoding" id="fs_fs_writesync_fd_data_position_encoding">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.5</span>
</div><p>Synchronous versions of <a href="#fs_fs_write_fd_buffer_offset_length_position_callback"><code>fs.write()</code></a>. Returns the number of bytes written.</p>
<!-- [end-include:fs.md] -->
<!-- [start-include:globals.md] -->
<h1>Global Objects<span><a class="mark" href="#globals_global_objects" id="globals_global_objects">#</a></span></h1>
<!-- type=misc -->
<p>These objects are available in all modules. Some of these objects aren't
actually in the global scope but in the module scope - this will be noted.</p>
<p>The objects listed here are specific to Node.js. There are a number of
<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>
<h2>Class: Buffer<span><a class="mark" href="#globals_class_buffer" id="globals_class_buffer">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.103</span>
</div><!-- type=global -->
<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>
<h2>__dirname<span><a class="mark" href="#globals_dirname" id="globals_dirname">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.27</span>
</div><!-- type=var -->
<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 the same as the
<a href="path.html#path_path_dirname_path"><code>path.dirname()</code></a> of the <a href="#globals_filename"><code>__filename</code></a>.</p>
<p><code>__dirname</code> isn't actually a global but rather local to each module.</p>
<p>Example: running <code>node example.js</code> from <code>/Users/mjr</code></p>
<pre><code class="lang-js">console.log(__dirname);
// Prints: /Users/mjr
console.log(path.dirname(__filename));
// Prints: /Users/mjr
</code></pre>
<h2>__filename<span><a class="mark" href="#globals_filename" id="globals_filename">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div><!-- type=var -->
<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 resolved absolute path of the
current module file.</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="#globals_dirname"><code>__dirname</code></a> for the directory name of the current module.</p>
<p><code>__filename</code> isn't actually a global but rather local to each module.</p>
<p>Examples:</p>
<p>Running <code>node example.js</code> from <code>/Users/mjr</code></p>
<pre><code class="lang-js">console.log(__filename);
// Prints: /Users/mjr/example.js
console.log(__dirname);
// Prints: /Users/mjr
</code></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>
<h2>clearImmediate(immediateObject)<span><a class="mark" href="#globals_clearimmediate_immediateobject" id="globals_clearimmediate_immediateobject">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div><!--type=global-->
<p><a href="timers.html#timers_clearimmediate_immediateobject"><code>clearImmediate</code></a> is described in the <a href="timers.html">timers</a> section.</p>
<h2>clearInterval(intervalObject)<span><a class="mark" href="#globals_clearinterval_intervalobject" id="globals_clearinterval_intervalobject">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div><!--type=global-->
<p><a href="timers.html#timers_clearinterval_intervalobject"><code>clearInterval</code></a> is described in the <a href="timers.html">timers</a> section.</p>
<h2>clearTimeout(timeoutObject)<span><a class="mark" href="#globals_cleartimeout_timeoutobject" id="globals_cleartimeout_timeoutobject">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div><!--type=global-->
<p><a href="timers.html#timers_cleartimeout_timeoutobject"><code>clearTimeout</code></a> is described in the <a href="timers.html">timers</a> section.</p>
<h2>console<span><a class="mark" href="#globals_console" id="globals_console">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.100</span>
</div><!-- type=global -->
<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>
<h2>exports<span><a class="mark" href="#globals_exports" id="globals_exports">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.12</span>
</div><!-- type=var -->
<p>A reference to the <code>module.exports</code> that is shorter to type.
See <a href="modules.html">module system documentation</a> for details on when to use <code>exports</code> and
when to use <code>module.exports</code>.</p>
<p><code>exports</code> isn't actually a global but rather local to each module.</p>
<p>See the <a href="modules.html">module system documentation</a> for more information.</p>
<h2>global<span><a class="mark" href="#globals_global" id="globals_global">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.27</span>
</div><!-- type=global -->
<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 is the global scope. That means that in
browsers if you're in the global scope <code>var something</code> will define a global
variable. In Node.js this is different. The top-level scope is not the global
scope; <code>var something</code> inside an Node.js module will be local to that module.</p>
<h2>module<span><a class="mark" href="#globals_module" id="globals_module">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div><!-- type=var -->
<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 module. In particular
<code>module.exports</code> is used for defining what a module exports and makes
available through <code>require()</code>.</p>
<p><code>module</code> isn't actually a global but rather local to each module.</p>
<p>See the <a href="modules.html">module system documentation</a> for more information.</p>
<h2>process<span><a class="mark" href="#globals_process" id="globals_process">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.7</span>
</div><!-- type=global -->
<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="process.html#process_process"><code>process</code> object</a> section.</p>
<h2>require()<span><a class="mark" href="#globals_require" id="globals_require">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.13</span>
</div><!-- type=var -->
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<p>To require modules. See the <a href="modules.html#modules_modules">Modules</a> section. <code>require</code> isn't actually a
global but rather local to each module.</p>
<h3>require.cache<span><a class="mark" href="#globals_require_cache" id="globals_require_cache">#</a></span></h3>
<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. Note that
this does not apply to <a href="addons.html">native addons</a>, for which reloading will result in an
Error.</p>
<h3>require.extensions<span><a class="mark" href="#globals_require_extensions" id="globals_require_extensions">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
<span>Deprecated since: v0.10.6 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated</pre><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="lang-js">require.extensions['.sjs'] = require.extensions['.js'];
</code></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>Since the Module system is locked, this feature will probably never go
away. However, it may have subtle bugs and complexities that are best
left untouched.</p>
<h3>require.resolve()<span><a class="mark" href="#globals_require_resolve" id="globals_require_resolve">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div><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>
<h2>setImmediate(callback[, arg][, ...])<span><a class="mark" href="#globals_setimmediate_callback_arg" id="globals_setimmediate_callback_arg">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div><!-- type=global -->
<p><a href="timers.html#timers_setimmediate_callback_arg"><code>setImmediate</code></a> is described in the <a href="timers.html">timers</a> section.</p>
<h2>setInterval(callback, delay[, arg][, ...])<span><a class="mark" href="#globals_setinterval_callback_delay_arg" id="globals_setinterval_callback_delay_arg">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div><!-- type=global -->
<p><a href="timers.html#timers_setinterval_callback_delay_arg"><code>setInterval</code></a> is described in the <a href="timers.html">timers</a> section.</p>
<h2>setTimeout(callback, delay[, arg][, ...])<span><a class="mark" href="#globals_settimeout_callback_delay_arg" id="globals_settimeout_callback_delay_arg">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div><!-- type=global -->
<p><a href="timers.html#timers_settimeout_callback_delay_arg"><code>setTimeout</code></a> is described in the <a href="timers.html">timers</a> section.</p>
<!-- [end-include:globals.md] -->
<!-- [start-include:http.md] -->
<h1>HTTP<span><a class="mark" href="#http_http" id="http_http">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>To use the HTTP server and client one must <code>require('http')</code>.</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--the
user is able to stream data.</p>
<p>HTTP message headers are represented by an object like this:</p>
<pre><code>{ 'content-length': '123',
'content-type': 'text/plain',
'connection': 'keep-alive',
'host': 'mysite.com',
'accept': '*/*' }
</code></pre><p>Keys are lowercased. Values are not modified.</p>
<p>In order to support the full spectrum of possible HTTP applications, Node.js's
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="#http_message_headers"><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>
<pre><code>[ 'ConTent-Length', '123456',
'content-LENGTH', '123',
'content-type', 'text/plain',
'CONNECTION', 'keep-alive',
'Host', 'mysite.com',
'accepT', '*/*' ]
</code></pre><h2>Class: http.Agent<span><a class="mark" href="#http_class_http_agent" id="http_class_http_agent">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.4</span>
</div><p>The HTTP Agent is used for pooling sockets used in HTTP client
requests.</p>
<p>The HTTP Agent also defaults client requests to using
Connection:keep-alive. If no pending HTTP requests are waiting on a
socket to become free the socket is closed. This means that Node.js's
pool has the benefit of keep-alive when under load but still does not
require developers to manually close the HTTP clients using
KeepAlive.</p>
<p>If you opt into using HTTP KeepAlive, you can create an Agent object
with that flag set to <code>true</code>. (See the <a href="#http_new_agent_options">constructor options</a>.)
Then, the Agent will keep unused sockets in a pool for later use. They
will be explicitly marked so as to not keep the Node.js process running.
However, it is still a good idea to explicitly <a href="#net_socket_destroy"><code>destroy()</code></a> KeepAlive
agents when they are no longer in use, so that the Sockets will be shut
down.</p>
<p>Sockets are removed from the agent's pool when the socket emits either
a <code>'close'</code> event or a special <code>'agentRemove'</code> event. This means that if
you intend to keep one HTTP request open for a long time and don't
want it to stay in the pool you can do something along the lines of:</p>
<pre><code class="lang-js">http.get(options, (res) => {
// Do stuff
}).on('socket', (socket) => {
socket.emit('agentRemove');
});
</code></pre>
<p>Alternatively, you could just opt out of pooling entirely using
<code>agent:false</code>:</p>
<pre><code class="lang-js">http.get({
hostname: 'localhost',
port: 80,
path: '/',
agent: false // create a new agent just for this one request
}, (res) => {
// Do stuff with response
})
</code></pre>
<h3>new Agent(<a href="#zlib_class_options">options</a>)<span><a class="mark" href="#http_new_agent_options" id="http_new_agent_options">#</a></span></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> 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. Default = <code>false</code></li>
<li><code>keepAliveMsecs</code> <span class="type"><Integer></span> When using the <code>keepAlive</code> option, specifies
the <a href="net.html#net_socket_setkeepalive_enable_initialdelay">initial delay</a>
for TCP Keep-Alive packets. Ignored when the
<code>keepAlive</code> option is <code>false</code> or <code>undefined</code>. Default = <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. Default = <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 to leave open
in a free state. Only relevant if <code>keepAlive</code> is set to <code>true</code>.
Default = <code>256</code>.</li>
</ul>
</li>
</ul>
<p>The default <a href="#http_http_globalagent"><code>http.globalAgent</code></a> that is used by <a href="http.html#http_http_request_options_callback"><code>http.request()</code></a> has all
of these values set to their respective defaults.</p>
<p>To configure any of them, you must create your own <a href="http.html#http_class_http_agent"><code>http.Agent</code></a> object.</p>
<pre><code class="lang-js">const http = require('http');
var keepAliveAgent = new http.Agent({ keepAlive: true });
options.agent = keepAliveAgent;
http.request(options, onResponseCallback);
</code></pre>
<h3>agent.destroy()<span><a class="mark" href="#http_agent_destroy" id="http_agent_destroy">#</a></span></h3>
<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 you are using an
agent with KeepAlive enabled, then it is best to explicitly shut down
the agent when you know that it will no longer be used. Otherwise,
sockets may hang open for quite a long time before the server
terminates them.</p>
<h3>agent.freeSockets<span><a class="mark" href="#http_agent_freesockets" id="http_agent_freesockets">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div><p>An object which contains arrays of sockets currently awaiting use by
the Agent when HTTP KeepAlive is used. Do not modify.</p>
<h3>agent.getName(options)<span><a class="mark" href="#http_agent_getname_options" id="http_agent_getname_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div><p>Get a unique name for a set of request options, to determine whether a
connection can be reused. In the http agent, this returns
<code>host:port:localAddress</code>. In the https agent, the name includes the
CA, cert, ciphers, and other HTTPS/TLS-specific options that determine
socket reusability.</p>
<p>Options:</p>
<ul>
<li><code>host</code>: A domain name or IP address of the server to issue the request to.</li>
<li><code>port</code>: Port of remote server.</li>
<li><code>localAddress</code>: Local interface to bind for network connections when issuing
the request.</li>
</ul>
<h3>agent.maxFreeSockets<span><a class="mark" href="#http_agent_maxfreesockets" id="http_agent_maxfreesockets">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.7</span>
</div><p>By default set to 256. For Agents supporting HTTP KeepAlive, this
sets the maximum number of sockets that will be left open in the free
state.</p>
<h3>agent.maxSockets<span><a class="mark" href="#http_agent_maxsockets" id="http_agent_maxsockets">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.6</span>
</div><p>By default set to Infinity. Determines how many concurrent sockets the agent
can have open per origin. Origin is either a 'host:port' or
'host:port:localAddress' combination.</p>
<h3>agent.requests<span><a class="mark" href="#http_agent_requests" id="http_agent_requests">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.9</span>
</div><p>An object which contains queues of requests that have not yet been assigned to
sockets. Do not modify.</p>
<h3>agent.sockets<span><a class="mark" href="#http_agent_sockets" id="http_agent_sockets">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.6</span>
</div><p>An object which contains arrays of sockets currently in use by the
Agent. Do not modify.</p>
<h2>Class: http.ClientRequest<span><a class="mark" href="#http_class_http_clientrequest" id="http_class_http_clientrequest">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.17</span>
</div><p>This object is created internally and returned from <a href="http.html#http_http_request_options_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 <code>setHeader(name, value)</code>, <code>getHeader(name)</code>,
<code>removeHeader(name)</code> API. The actual header will be sent along with the first
data chunk or when closing the connection.</p>
<p>To get the response, add a listener for <code>'response'</code> to the request object.
<code>'response'</code> will be emitted from the request object when the response
headers have been received. The <code>'response'</code> event is executed with one
argument which is an instance of <a href="#http_class_http_incomingmessage"><code>http.IncomingMessage</code></a>.</p>
<p>During the <code>'response'</code> event, one can add listeners to the
response object; particularly to listen for the <code>'data'</code> event.</p>
<p>If no <code>'response'</code> handler is added, then the response will be
entirely discarded. However, if you add a <code>'response'</code> event handler,
then you <strong>must</strong> consume the data from the response object, 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>Note: Node.js does not check whether Content-Length and the length of the body
which has been transmitted are equal or not.</p>
<p>The request implements the <a href="stream.html#stream_class_stream_writable">Writable Stream</a> interface. This is an
<a href="events.html#events_class_eventemitter"><code>EventEmitter</code></a> with the following events:</p>
<h3>Event: 'abort'<span><a class="mark" href="#http_event_abort" id="http_event_abort">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.4.1</span>
</div><p><code>function () { }</code></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>
<h3>Event: 'aborted'<span><a class="mark" href="#http_event_aborted" id="http_event_aborted">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.8</span>
</div><p><code>function () { }</code></p>
<p>Emitted when the request has been aborted by the server and the network
socket has closed.</p>
<h3>Event: 'connect'<span><a class="mark" href="#http_event_connect" id="http_event_connect">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div><p><code>function (response, socket, head) { }</code></p>
<p>Emitted each time a server responds to a request with a <code>CONNECT</code> method. If this
event isn't being listened for, clients receiving a <code>CONNECT</code> method will have
their connections closed.</p>
<p>A client and server pair that shows you how to listen for the <code>'connect'</code> event:</p>
<pre><code class="lang-js">const http = require('http');
const net = require('net');
const url = require('url');
// Create an HTTP tunneling proxy
var proxy = http.createServer( (req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('okay');
});
proxy.on('connect', (req, cltSocket, head) => {
// connect to an origin server
var srvUrl = url.parse(`http://${req.url}`);
var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, () => {
cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
'Proxy-agent: Node.js-Proxy\r\n' +
'\r\n');
srvSocket.write(head);
srvSocket.pipe(cltSocket);
cltSocket.pipe(srvSocket);
});
});
// now that proxy is running
proxy.listen(1337, '127.0.0.1', () => {
// make a request to a tunneling proxy
var options = {
port: 1337,
hostname: '127.0.0.1',
method: 'CONNECT',
path: 'www.google.com:80'
};
var req = http.request(options);
req.end();
req.on('connect', (res, socket, head) => {
console.log('got connected!');
// make a request over an HTTP tunnel
socket.write('GET / HTTP/1.1\r\n' +
'Host: www.google.com:80\r\n' +
'Connection: close\r\n' +
'\r\n');
socket.on('data', (chunk) => {
console.log(chunk.toString());
});
socket.on('end', () => {
proxy.close();
});
});
});
</code></pre>
<h3>Event: 'continue'<span><a class="mark" href="#http_event_continue" id="http_event_continue">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.2</span>
</div><p><code>function () { }</code></p>
<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>
<h3>Event: 'response'<span><a class="mark" href="#http_event_response" id="http_event_response">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.0</span>
</div><p><code>function (response) { }</code></p>
<p>Emitted when a response is received to this request. This event is emitted only
once. The <code>response</code> argument will be an instance of <a href="#http_class_http_incomingmessage"><code>http.IncomingMessage</code></a>.</p>
<h3>Event: 'socket'<span><a class="mark" href="#http_event_socket" id="http_event_socket">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.3</span>
</div><p><code>function (socket) { }</code></p>
<p>Emitted after a socket is assigned to this request.</p>
<h3>Event: 'upgrade'<span><a class="mark" href="#http_event_upgrade" id="http_event_upgrade">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div><p><code>function (response, socket, head) { }</code></p>
<p>Emitted each time a server responds to a request with an upgrade. If this
event isn't being listened for, clients receiving an upgrade header will have
their connections closed.</p>
<p>A client server pair that show you how to listen for the <code>'upgrade'</code> event.</p>
<pre><code class="lang-js">const http = require('http');
// Create an HTTP server
var srv = http.createServer( (req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('okay');
});
srv.on('upgrade', (req, socket, head) => {
socket.write('HTTP/1.1 101 Web Socket Protocol Handshake\r\n' +
'Upgrade: WebSocket\r\n' +
'Connection: Upgrade\r\n' +
'\r\n');
socket.pipe(socket); // echo back
});
// now that server is running
srv.listen(1337, '127.0.0.1', () => {
// make a request
var options = {
port: 1337,
hostname: '127.0.0.1',
headers: {
'Connection': 'Upgrade',
'Upgrade': 'websocket'
}
};
var req = http.request(options);
req.end();
req.on('upgrade', (res, socket, upgradeHead) => {
console.log('got upgraded!');
socket.end();
process.exit(0);
});
});
</code></pre>
<h3>request.abort()<span><a class="mark" href="#http_request_abort" id="http_request_abort">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.8</span>
</div><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>
<h3>request.aborted<span><a class="mark" href="#http_request_aborted" id="http_request_aborted">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div><p>If a request has been aborted, this value is the time when the request was
aborted, in milliseconds since 1 January 1970 00:00:00 UTC.</p>
<h3>request.end([data][, encoding][, callback])<span><a class="mark" href="#http_request_end_data_encoding_callback" id="http_request_end_data_encoding_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><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="#http_response_write_chunk_encoding_callback"><code>response.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>
<h3>request.flushHeaders()<span><a class="mark" href="#http_request_flushheaders" id="http_request_flushheaders">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v1.6.0</span>
</div><p>Flush the request headers.</p>
<p>For efficiency reasons, Node.js normally buffers the request headers until you
call <code>request.end()</code> or write the first chunk of request data. It then tries
hard to pack the request headers and data into a single TCP packet.</p>
<p>That's usually what you want (it saves a TCP round-trip) but not when the first
data isn't sent until possibly much later. <code>request.flushHeaders()</code> lets you bypass
the optimization and kickstart the request.</p>
<h3>request.setNoDelay([noDelay])<span><a class="mark" href="#http_request_setnodelay_nodelay" id="http_request_setnodelay_nodelay">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.9</span>
</div><p>Once a socket is assigned to this request and is connected
<a href="net.html#net_socket_setnodelay_nodelay"><code>socket.setNoDelay()</code></a> will be called.</p>
<h3>request.setSocketKeepAlive([enable][, initialDelay])<span><a class="mark" href="#http_request_setsocketkeepalive_enable_initialdelay" id="http_request_setsocketkeepalive_enable_initialdelay">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.9</span>
</div><p>Once a socket is assigned to this request and is connected
<a href="net.html#net_socket_setkeepalive_enable_initialdelay"><code>socket.setKeepAlive()</code></a> will be called.</p>
<h3>request.setTimeout(timeout[, callback])<span><a class="mark" href="#http_request_settimeout_timeout_callback" id="http_request_settimeout_timeout_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.9</span>
</div><p>Once a socket is assigned to this request and is connected
<a href="#net_socket_settimeout_timeout_callback"><code>socket.setTimeout()</code></a> will be called.</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> Milliseconds before a request is considered to be timed 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>
</ul>
<p>Returns <code>request</code>.</p>
<h3>request.write(chunk[, encoding][, callback])<span><a class="mark" href="#http_request_write_chunk_encoding_callback" id="http_request_write_chunk_encoding_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.29</span>
</div><p>Sends a chunk of the body. By calling this method
many times, the user can stream a request body to a
server--in that case it is suggested to use the
<code>['Transfer-Encoding', 'chunked']</code> header line when
creating the request.</p>
<p>The <code>chunk</code> argument should be a <a href="buffer.html#buffer_buffer"><code>Buffer</code></a> or a string.</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.</p>
<p>Returns <code>request</code>.</p>
<h2>Class: http.Server<span><a class="mark" href="#http_class_http_server" id="http_class_http_server">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.17</span>
</div><p>This class inherits from <a href="net.html#net_class_net_server"><code>net.Server</code></a> and has the following additional events:</p>
<h3>Event: 'checkContinue'<span><a class="mark" href="#http_event_checkcontinue" id="http_event_checkcontinue">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div><p><code>function (request, response) { }</code></p>
<p>Emitted each time a request with an http Expect: 100-continue is received.
If this event isn't listened for, the server will automatically respond
with a 100 Continue as appropriate.</p>
<p>Handling this event involves calling <a href="#http_response_writecontinue"><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>Note that when this event is emitted and handled, the <code>'request'</code> event will
not be emitted.</p>
<h3>Event: 'clientError'<span><a class="mark" href="#http_event_clienterror" id="http_event_clienterror">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div><p><code>function (exception, socket) { }</code></p>
<p>If a client connection emits an <code>'error'</code> event, it will be forwarded here.</p>
<p><code>socket</code> is the <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> object that the error originated from.</p>
<h3>Event: 'close'<span><a class="mark" href="#http_event_close" id="http_event_close">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.4</span>
</div><p><code>function () { }</code></p>
<p>Emitted when the server closes.</p>
<h3>Event: 'connect'<span><a class="mark" href="#http_event_connect_1" id="http_event_connect_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div><p><code>function (request, socket, head) { }</code></p>
<p>Emitted each time a client requests a http <code>CONNECT</code> method. If this event isn't
listened for, then clients requesting a <code>CONNECT</code> method will have their
connections closed.</p>
<ul>
<li><code>request</code> is the arguments for the http request, as it is in the request
event.</li>
<li><code>socket</code> is the network socket between the server and client.</li>
<li><code>head</code> is an instance of Buffer, the first packet of the tunneling stream,
this may be empty.</li>
</ul>
<p>After this event is emitted, the request's socket will not have a <code>'data'</code>
event listener, meaning you will need to bind to it in order to handle data
sent to the server on that socket.</p>
<h3>Event: 'connection'<span><a class="mark" href="#http_event_connection" id="http_event_connection">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.0</span>
</div><p><code>function (socket) { }</code></p>
<p>When a new TCP stream is established. <code>socket</code> is an object of type
<a href="net.html#net_class_net_socket"><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.connection</code>.</p>
<h3>Event: 'request'<span><a class="mark" href="#http_event_request" id="http_event_request">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.0</span>
</div><p><code>function (request, response) { }</code></p>
<p>Emitted each time there is a request. Note that there may be multiple requests
per connection (in the case of keep-alive connections).
<code>request</code> is an instance of <a href="#http_class_http_incomingmessage"><code>http.IncomingMessage</code></a> and <code>response</code> is
an instance of <a href="#http_class_http_serverresponse"><code>http.ServerResponse</code></a>.</p>
<h3>Event: 'upgrade'<span><a class="mark" href="#http_event_upgrade_1" id="http_event_upgrade_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.94</span>
</div><p><code>function (request, socket, head) { }</code></p>
<p>Emitted each time a client requests a http upgrade. If this event isn't
listened for, then clients requesting an upgrade will have their connections
closed.</p>
<ul>
<li><code>request</code> is the arguments for the http request, as it is in the request
event.</li>
<li><code>socket</code> is the network socket between the server and client.</li>
<li><code>head</code> is an instance of Buffer, the first packet of the upgraded stream,
this may be empty.</li>
</ul>
<p>After this event is emitted, the request's socket will not have a <code>'data'</code>
event listener, meaning you will need to bind to it in order to handle data
sent to the server on that socket.</p>
<h3>server.close([callback])<span><a class="mark" href="#http_server_close_callback" id="http_server_close_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>Stops the server from accepting new connections. See <a href="net.html#net_server_close_callback"><code>net.Server.close()</code></a>.</p>
<h3>server.listen(handle[, callback])<span><a class="mark" href="#http_server_listen_handle_callback" id="http_server_listen_handle_callback">#</a></span></h3>
<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>callback</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function" class="type"><Function></a></li>
</ul>
<p>The <code>handle</code> object can be set to either a server or socket (anything
with an underlying <code>_handle</code> member), or a <code>{fd: <n>}</code> object.</p>
<p>This will cause the server to accept connections on the specified
handle, but it is presumed that the file descriptor or handle has
already been bound to a port or domain socket.</p>
<p>Listening on a file descriptor is not supported on Windows.</p>
<p>This function is asynchronous. <code>callback</code> will be added as a listener for the
<code>'listening'</code> event. See also <a href="net.html#net_server_listen_handle_callback"><code>net.Server.listen()</code></a>.</p>
<p>Returns <code>server</code>.</p>
<h3>server.listen(path[, callback])<span><a class="mark" href="#http_server_listen_path_callback" id="http_server_listen_path_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>Start a UNIX socket server listening for connections on the given <code>path</code>.</p>
<p>This function is asynchronous. <code>callback</code> will be added as a listener for the
<code>'listening'</code> event. See also <a href="net.html#net_server_listen_path_callback"><code>net.Server.listen(path)</code></a>.</p>
<h3>server.listen([port][, hostname][, backlog][, callback])<span><a class="mark" href="#http_server_listen_port_hostname_backlog_callback" id="http_server_listen_port_hostname_backlog_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>Begin accepting connections on the specified <code>port</code> and <code>hostname</code>. If the
<code>hostname</code> is omitted, the server will accept connections on any IPv6 address
(<code>::</code>) when IPv6 is available, or any IPv4 address (<code>0.0.0.0</code>) otherwise.
Omit the port argument, or use a port value of <code>0</code>, to have the operating system
assign a random port, which can be retrieved by using <code>server.address().port</code>
after the <code>'listening'</code> event has been emitted.</p>
<p>To listen to a unix socket, supply a filename instead of port and hostname.</p>
<p>Backlog is the maximum length of the queue of pending connections.
The actual length will be determined by your 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>This function is asynchronous. <code>callback</code> will be added as a listener for the
<code>'listening'</code> event. See also <a href="net.html#net_server_listen_port_hostname_backlog_callback"><code>net.Server.listen(port)</code></a>.</p>
<h3>server.maxHeadersCount<span><a class="mark" href="#http_server_maxheaderscount" id="http_server_maxheaderscount">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div><p>Limits maximum incoming headers count, equal to 1000 by default. If set to 0 -
no limit will be applied.</p>
<h3>server.setTimeout(msecs, callback)<span><a class="mark" href="#http_server_settimeout_msecs_callback" id="http_server_settimeout_msecs_callback">#</a></span></h3>
<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>
</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's timeout value is 2 minutes, and sockets are
destroyed automatically if they time out. However, if you assign a
callback to the Server's <code>'timeout'</code> event, then you are responsible
for handling socket timeouts.</p>
<p>Returns <code>server</code>.</p>
<h3>server.timeout<span><a class="mark" href="#http_server_timeout" id="http_server_timeout">#</a></span></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#Number_type" class="type"><Number></a> Default = 120000 (2 minutes)</li>
</ul>
<p>The number of milliseconds of inactivity before a socket is presumed
to have timed out.</p>
<p>Note that the socket timeout logic is set up on connection, so
changing this value only affects <em>new</em> connections to the server, not
any existing connections.</p>
<p>Set to 0 to disable any kind of automatic timeout behavior on incoming
connections.</p>
<h2>Class: http.ServerResponse<span><a class="mark" href="#http_class_http_serverresponse" id="http_class_http_serverresponse">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.17</span>
</div><p>This object is created internally by a HTTP server--not by the user. It is
passed as the second parameter to the <code>'request'</code> event.</p>
<p>The response implements, but does not inherit from, the <a href="stream.html#stream_class_stream_writable">Writable Stream</a>
interface. This is an <a href="events.html#events_class_eventemitter"><code>EventEmitter</code></a> with the following events:</p>
<h3>Event: 'close'<span><a class="mark" href="#http_event_close_1" id="http_event_close_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.6.7</span>
</div><p><code>function () { }</code></p>
<p>Indicates that the underlying connection was terminated before
<a href="#http_response_end_data_encoding_callback"><code>response.end()</code></a> was called or able to flush.</p>
<h3>Event: 'finish'<span><a class="mark" href="#http_event_finish" id="http_event_finish">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.6</span>
</div><p><code>function () { }</code></p>
<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>
<p>After this event, no more events will be emitted on the response object.</p>
<h3>response.addTrailers(headers)<span><a class="mark" href="#http_response_addtrailers_headers" id="http_response_addtrailers_headers">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div><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>Note that HTTP requires the <code>Trailer</code> header to be sent if you intend to
emit trailers, with a list of the header fields in its value. E.g.,</p>
<pre><code class="lang-js">response.writeHead(200, { 'Content-Type': 'text/plain',
'Trailer': 'Content-MD5' });
response.write(fileData);
response.addTrailers({'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667'});
response.end();
</code></pre>
<p>Attempting to set a header field name or value that contains invalid characters
will result in a <a href="errors.html#errors_class_typeerror"><code>TypeError</code></a> being thrown.</p>
<h3>response.end([data][, encoding][, callback])<span><a class="mark" href="#http_response_end_data_encoding_callback" id="http_response_end_data_encoding_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><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="#http_response_write_chunk_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>
<h3>response.finished<span><a class="mark" href="#http_response_finished" id="http_response_finished">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.0.2</span>
</div><p>Boolean value that indicates whether the response has completed. Starts
as <code>false</code>. After <a href="#http_response_end_data_encoding_callback"><code>response.end()</code></a> executes, the value will be <code>true</code>.</p>
<h3>response.getHeader(name)<span><a class="mark" href="#http_response_getheader_name" id="http_response_getheader_name">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.4.0</span>
</div><p>Reads out a header that's already been queued but not sent to the client. Note
that the name is case insensitive. This can only be called before headers get
implicitly flushed.</p>
<p>Example:</p>
<pre><code class="lang-js">var contentType = response.getHeader('content-type');
</code></pre>
<h3>response.headersSent<span><a class="mark" href="#http_response_headerssent" id="http_response_headerssent">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.3</span>
</div><p>Boolean (read-only). True if headers were sent, false otherwise.</p>
<h3>response.removeHeader(name)<span><a class="mark" href="#http_response_removeheader_name" id="http_response_removeheader_name">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.4.0</span>
</div><p>Removes a header that's queued for implicit sending.</p>
<p>Example:</p>
<pre><code class="lang-js">response.removeHeader('Content-Encoding');
</code></pre>
<h3>response.sendDate<span><a class="mark" href="#http_response_senddate" id="http_response_senddate">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.5</span>
</div><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>
<h3>response.setHeader(name, value)<span><a class="mark" href="#http_response_setheader_name_value" id="http_response_setheader_name_value">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.4.0</span>
</div><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 if you need to send multiple headers with the same name.</p>
<p>Example:</p>
<pre><code class="lang-js">response.setHeader('Content-Type', 'text/html');
</code></pre>
<p>or</p>
<pre><code class="lang-js">response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']);
</code></pre>
<p>Attempting to set a header field name or value that contains invalid characters
will result in a <a href="errors.html#errors_class_typeerror"><code>TypeError</code></a> being thrown.</p>
<p>When headers have been set with <a href="#http_response_setheader_name_value"><code>response.setHeader()</code></a>, they will be merged with
any headers passed to <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a>, with the headers passed to
<a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> given precedence.</p>
<pre><code class="lang-js">// returns content-type = text/plain
const server = http.createServer((req,res) => {
res.setHeader('Content-Type', 'text/html');
res.setHeader('X-Foo', 'bar');
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('ok');
});
</code></pre>
<h3>response.setTimeout(msecs, callback)<span><a class="mark" href="#http_response_settimeout_msecs_callback" id="http_response_settimeout_msecs_callback">#</a></span></h3>
<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>
</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 you
assign a handler on the request, the response, or the server's
<code>'timeout'</code> events, then it is your responsibility to handle timed out
sockets.</p>
<p>Returns <code>response</code>.</p>
<h3>response.statusCode<span><a class="mark" href="#http_response_statuscode" id="http_response_statuscode">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.4.0</span>
</div><p>When using implicit headers (not calling <a href="#http_response_writehead_statuscode_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>
<p>Example:</p>
<pre><code class="lang-js">response.statusCode = 404;
</code></pre>
<p>After response header was sent to the client, this property indicates the
status code which was sent out.</p>
<h3>response.statusMessage<span><a class="mark" href="#http_response_statusmessage" id="http_response_statusmessage">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.8</span>
</div><p>When using implicit headers (not calling <a href="#http_response_writehead_statuscode_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>
<p>Example:</p>
<pre><code class="lang-js">response.statusMessage = 'Not found';
</code></pre>
<p>After response header was sent to the client, this property indicates the
status message which was sent out.</p>
<h3>response.write(chunk[, encoding][, callback])<span><a class="mark" href="#http_response_write_chunk_encoding_callback" id="http_response_write_chunk_encoding_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.29</span>
</div><p>If this method is called and <a href="#http_response_writehead_statuscode_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><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><strong>Note</strong>: 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="#http_response_write_chunk_encoding_callback"><code>response.write()</code></a> is called, it will send the buffered
header information and the first body to the client. The second time
<a href="#http_response_write_chunk_encoding_callback"><code>response.write()</code></a> is called, Node.js assumes you're going to be streaming
data, and sends that separately. That is, the response is buffered up to the
first chunk of 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>
<h3>response.writeContinue()<span><a class="mark" href="#http_response_writecontinue" id="http_response_writecontinue">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div><p>Sends a HTTP/1.1 100 Continue message to the client, indicating that
the request body should be sent. See the <a href="#http_event_checkcontinue"><code>'checkContinue'</code></a> event on <code>Server</code>.</p>
<h3>response.writeHead(statusCode[, statusMessage][, headers])<span><a class="mark" href="#http_response_writehead_statuscode_statusmessage_headers" id="http_response_writehead_statuscode_statusmessage_headers">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.30</span>
</div><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>Example:</p>
<pre><code class="lang-js">var body = 'hello world';
response.writeHead(200, {
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'text/plain' });
</code></pre>
<p>This method must only be called once on a message and it must
be called before <a href="#http_response_end_data_encoding_callback"><code>response.end()</code></a> is called.</p>
<p>If you call <a href="#http_response_write_chunk_encoding_callback"><code>response.write()</code></a> or <a href="#http_response_end_data_encoding_callback"><code>response.end()</code></a> before calling this,
the implicit/mutable headers will be calculated and call this function for you.</p>
<p>When headers have been set with <a href="#http_response_setheader_name_value"><code>response.setHeader()</code></a>, they will be merged with
any headers passed to <a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a>, with the headers passed to
<a href="#http_response_writehead_statuscode_statusmessage_headers"><code>response.writeHead()</code></a> given precedence.</p>
<pre><code class="lang-js">// returns content-type = text/plain
const server = http.createServer((req,res) => {
res.setHeader('Content-Type', 'text/html');
res.setHeader('X-Foo', 'bar');
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('ok');
});
</code></pre>
<p>Note that Content-Length is given in bytes not characters. The above example
works because the string <code>'hello world'</code> contains only single byte characters.
If the body contains higher coded characters then <code>Buffer.byteLength()</code>
should be used to determine the number of bytes in a given encoding.
And Node.js does not check whether Content-Length 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 <a href="errors.html#errors_class_typeerror"><code>TypeError</code></a> being thrown.</p>
<h2>Class: http.IncomingMessage<span><a class="mark" href="#http_class_http_incomingmessage" id="http_class_http_incomingmessage">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.17</span>
</div><p>An <code>IncomingMessage</code> object is created by <a href="http.html#http_class_http_server"><code>http.Server</code></a> or
<a href="#http_class_http_clientrequest"><code>http.ClientRequest</code></a> and passed as the first argument to the <code>'request'</code>
and <code>'response'</code> event respectively. It may be used to access response status,
headers and data.</p>
<p>It implements the <a href="stream.html#stream_class_stream_readable">Readable Stream</a> interface, as well as the
following additional events, methods, and properties.</p>
<h3>Event: 'aborted'<span><a class="mark" href="#http_event_aborted_1" id="http_event_aborted_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.8</span>
</div><p><code>function () { }</code></p>
<p>Emitted when the request has been aborted by the client and the network
socket has closed.</p>
<h3>Event: 'close'<span><a class="mark" href="#http_event_close_2" id="http_event_close_2">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.4.2</span>
</div><p><code>function () { }</code></p>
<p>Indicates that the underlying connection was closed.
Just like <code>'end'</code>, this event occurs only once per response.</p>
<h3>message.destroy([error])<span><a class="mark" href="#http_message_destroy_error" id="http_message_destroy_error">#</a></span></h3>
<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></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 and <code>error</code> is passed as an argument
to any listeners on the event.</p>
<h3>message.headers<span><a class="mark" href="#http_message_headers" id="http_message_headers">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.5</span>
</div><p>The request/response headers object.</p>
<p>Key-value pairs of header names and values. Header names are lower-cased.
Example:</p>
<pre><code class="lang-js">// Prints something like:
//
// { 'user-agent': 'curl/7.22.0',
// host: '127.0.0.1:8000',
// accept: '*/*' }
console.log(request.headers);
</code></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>, or <code>user-agent</code> are discarded.</li>
<li><code>set-cookie</code> is always an array. Duplicates are added to the array.</li>
<li>For all other headers, the values are joined together with ', '.</li>
</ul>
<h3>message.httpVersion<span><a class="mark" href="#http_message_httpversion" id="http_message_httpversion">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.1</span>
</div><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>
<h3>message.method<span><a class="mark" href="#http_message_method" id="http_message_method">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.1</span>
</div><p><strong>Only valid for request obtained from <a href="http.html#http_class_http_server"><code>http.Server</code></a>.</strong></p>
<p>The request method as a string. Read only. Example:
<code>'GET'</code>, <code>'DELETE'</code>.</p>
<h3>message.rawHeaders<span><a class="mark" href="#http_message_rawheaders" id="http_message_rawheaders">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.6</span>
</div><p>The raw request/response headers list exactly as they were received.</p>
<p>Note that 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="lang-js">// Prints something like:
//
// [ 'user-agent',
// 'this is invalid because there can be only one',
// 'User-Agent',
// 'curl/7.22.0',
// 'Host',
// '127.0.0.1:8000',
// 'ACCEPT',
// '*/*' ]
console.log(request.rawHeaders);
</code></pre>
<h3>message.rawTrailers<span><a class="mark" href="#http_message_rawtrailers" id="http_message_rawtrailers">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.6</span>
</div><p>The raw request/response trailer keys and values exactly as they were
received. Only populated at the <code>'end'</code> event.</p>
<h3>message.setTimeout(msecs, callback)<span><a class="mark" href="#http_message_settimeout_msecs_callback" id="http_message_settimeout_msecs_callback">#</a></span></h3>
<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>
</ul>
<p>Calls <code>message.connection.setTimeout(msecs, callback)</code>.</p>
<p>Returns <code>message</code>.</p>
<h3>message.statusCode<span><a class="mark" href="#http_message_statuscode" id="http_message_statuscode">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.1</span>
</div><p><strong>Only valid for response obtained from <a href="#http_class_http_clientrequest"><code>http.ClientRequest</code></a>.</strong></p>
<p>The 3-digit HTTP response status code. E.G. <code>404</code>.</p>
<h3>message.statusMessage<span><a class="mark" href="#http_message_statusmessage" id="http_message_statusmessage">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.10</span>
</div><p><strong>Only valid for response obtained from <a href="#http_class_http_clientrequest"><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>
<h3>message.socket<span><a class="mark" href="#http_message_socket" id="http_message_socket">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div><p>The <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> object associated with the connection.</p>
<p>With HTTPS support, use <a href="tls.html#tls_tlssocket_getpeercertificate_detailed"><code>request.socket.getPeerCertificate()</code></a> to obtain the
client's authentication details.</p>
<h3>message.trailers<span><a class="mark" href="#http_message_trailers" id="http_message_trailers">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div><p>The request/response trailers object. Only populated at the <code>'end'</code> event.</p>
<h3>message.url<span><a class="mark" href="#http_message_url" id="http_message_url">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p><strong>Only valid for request obtained from <a href="http.html#http_class_http_server"><code>http.Server</code></a>.</strong></p>
<p>Request URL string. This contains only the URL that is
present in the actual HTTP request. If the request is:</p>
<pre><code>GET /status?name=ryan HTTP/1.1\r\n
Accept: text/plain\r\n
\r\n
</code></pre><p>Then <code>request.url</code> will be:</p>
<pre><code>'/status?name=ryan'
</code></pre><p>If you would like to parse the URL into its parts, you can use
<code>require('url').parse(request.url)</code>. Example:</p>
<pre><code>$ node
> require('url').parse('/status?name=ryan')
{
href: '/status?name=ryan',
search: '?name=ryan',
query: 'name=ryan',
pathname: '/status'
}
</code></pre><p>If you would like to extract the parameters from the query string,
you can use the <code>require('querystring').parse</code> function, or pass
<code>true</code> as the second argument to <code>require('url').parse</code>. Example:</p>
<pre><code>$ node
> require('url').parse('/status?name=ryan', true)
{
href: '/status?name=ryan',
search: '?name=ryan',
query: {name: 'ryan'},
pathname: '/status'
}
</code></pre><h2>http.METHODS<span><a class="mark" href="#http_http_methods" id="http_http_methods">#</a></span></h2>
<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/Reference/Global_Objects/Array" class="type"><Array></a></li>
</ul>
<p>A list of the HTTP methods that are supported by the parser.</p>
<h2>http.STATUS_CODES<span><a class="mark" href="#http_http_status_codes" id="http_http_status_codes">#</a></span></h2>
<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>
<h2>http.createClient([port][, host])<span><a class="mark" href="#http_http_createclient_port_host" id="http_http_createclient_port_host">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.13</span>
<span>Deprecated since: v0.3.6 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated: Use <a href="http.html#http_http_request_options_callback"><code>http.request()</code></a> instead.</pre><p>Constructs a new HTTP client. <code>port</code> and <code>host</code> refer to the server to be
connected to.</p>
<h2>http.createServer([requestListener])<span><a class="mark" href="#http_http_createserver_requestlistener" id="http_http_createserver_requestlistener">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.13</span>
</div><p>Returns a new instance of <a href="http.html#http_class_http_server"><code>http.Server</code></a>.</p>
<p>The <code>requestListener</code> is a function which is automatically
added to the <code>'request'</code> event.</p>
<h2>http.get(options[, callback])<span><a class="mark" href="#http_http_get_options_callback" id="http_http_get_options_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.6</span>
</div><p>Since most requests are GET requests without bodies, Node.js provides this
convenience method. The only difference between this method and <a href="http.html#http_http_request_options_callback"><code>http.request()</code></a>
is that it sets the method to GET and calls <code>req.end()</code> automatically.</p>
<p>Example:</p>
<pre><code class="lang-js">http.get('http://www.google.com/index.html', (res) => {
console.log(`Got response: ${res.statusCode}`);
// consume response body
res.resume();
}).on('error', (e) => {
console.log(`Got error: ${e.message}`);
});
</code></pre>
<h2>http.globalAgent<span><a class="mark" href="#http_http_globalagent" id="http_http_globalagent">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.9</span>
</div><p>Global instance of Agent which is used as the default for all http client
requests.</p>
<h2>http.request(options[, callback])<span><a class="mark" href="#http_http_request_options_callback" id="http_http_request_options_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.6</span>
</div><p>Node.js maintains several connections per server to make HTTP requests.
This function allows one to transparently issue requests.</p>
<p><code>options</code> can be an object or a string. If <code>options</code> is a string, it is
automatically parsed with <a href="url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost"><code>url.parse()</code></a>.</p>
<p>Options:</p>
<ul>
<li><code>protocol</code>: Protocol to use. Defaults to <code>'http:'</code>.</li>
<li><code>host</code>: A domain name or IP address of the server to issue the request to.
Defaults to <code>'localhost'</code>.</li>
<li><code>hostname</code>: Alias for <code>host</code>. To support <a href="url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost"><code>url.parse()</code></a> <code>hostname</code> is
preferred over <code>host</code>.</li>
<li><code>family</code>: IP address family to use when resolving <code>host</code> and <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>port</code>: Port of remote server. Defaults to 80.</li>
<li><code>localAddress</code>: Local interface to bind for network connections.</li>
<li><code>socketPath</code>: Unix Domain Socket (use one of host:port or socketPath).</li>
<li><code>method</code>: A string specifying the HTTP request method. Defaults to <code>'GET'</code>.</li>
<li><code>path</code>: Request path. Defaults to <code>'/'</code>. 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>headers</code>: An object containing request headers.</li>
<li><code>auth</code>: Basic authentication i.e. <code>'user:password'</code> to compute an
Authorization header.</li>
<li><code>agent</code>: Controls <a href="#https_class_https_agent"><code>Agent</code></a> behavior. When an Agent is used request will
default to <code>Connection: keep-alive</code>. Possible values:<ul>
<li><code>undefined</code> (default): use <a href="#http_http_globalagent"><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>: opts out of connection pooling with an Agent, defaults request to
<code>Connection: close</code>.</li>
</ul>
</li>
</ul>
<p>The optional <code>callback</code> parameter will be added as a one time listener for
the <code>'response'</code> event.</p>
<p><code>http.request()</code> returns an instance of the <a href="#http_class_http_clientrequest"><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>
<p>Example:</p>
<pre><code class="lang-js">var postData = querystring.stringify({
'msg' : 'Hello World!'
});
var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': Buffer.byteLength(postData)
}
};
var req = http.request(options, (res) => {
console.log(`STATUS: ${res.statusCode}`);
console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.')
})
});
req.on('error', (e) => {
console.log(`problem with request: ${e.message}`);
});
// write data to request body
req.write(postData);
req.end();
</code></pre>
<p>Note that in the example <code>req.end()</code> was called. With <code>http.request()</code> one
must always call <code>req.end()</code> to signify that you're done with 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', you should both set a timeout
and listen for the <code>'continue'</code> event. See RFC2616 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>
<!-- [end-include:http.md] -->
<!-- [start-include:https.md] -->
<h1>HTTPS<span><a class="mark" href="#https_https" id="https_https">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a
separate module.</p>
<h2>Class: https.Agent<span><a class="mark" href="#https_class_https_agent" id="https_class_https_agent">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.4.5</span>
</div><p>An Agent object for HTTPS similar to <a href="http.html#http_class_http_agent"><code>http.Agent</code></a>. See <a href="#https_https_request_options_callback"><code>https.request()</code></a>
for more information.</p>
<h2>Class: https.Server<span><a class="mark" href="#https_class_https_server" id="https_class_https_server">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.4</span>
</div><p>This class is a subclass of <code>tls.Server</code> and emits events same as
<a href="http.html#http_class_http_server"><code>http.Server</code></a>. See <a href="http.html#http_class_http_server"><code>http.Server</code></a> for more information.</p>
<h3>server.setTimeout(msecs, callback)<span><a class="mark" href="#https_server_settimeout_msecs_callback" id="https_server_settimeout_msecs_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.2</span>
</div><p>See <a href="http.html#http_server_settimeout_msecs_callback"><code>http.Server#setTimeout()</code></a>.</p>
<h3>server.timeout<span><a class="mark" href="#https_server_timeout" id="https_server_timeout">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.2</span>
</div><p>See <a href="http.html#http_server_timeout"><code>http.Server#timeout</code></a>.</p>
<h2>https.createServer(options[, requestListener])<span><a class="mark" href="#https_https_createserver_options_requestlistener" id="https_https_createserver_options_requestlistener">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.4</span>
</div><p>Returns a new HTTPS web server object. The <code>options</code> is similar to
<a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a>. The <code>requestListener</code> is a function which is
automatically added to the <code>'request'</code> event.</p>
<p>Example:</p>
<pre><code class="lang-js">// curl -k https://localhost:8000/
const https = require('https');
const fs = require('fs');
const options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
</code></pre>
<p>Or</p>
<pre><code class="lang-js">const https = require('https');
const fs = require('fs');
const options = {
pfx: fs.readFileSync('server.pfx')
};
https.createServer(options, (req, res) => {
res.writeHead(200);
res.end('hello world\n');
}).listen(8000);
</code></pre>
<h3>server.close([callback])<span><a class="mark" href="#https_server_close_callback" id="https_server_close_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>See <a href="http.html#http_server_close_callback"><code>http.close()</code></a> for details.</p>
<h3>server.listen(handle[, callback])<span><a class="mark" href="#https_server_listen_handle_callback" id="https_server_listen_handle_callback">#</a></span></h3>
<h3>server.listen(path[, callback])<span><a class="mark" href="#https_server_listen_path_callback" id="https_server_listen_path_callback">#</a></span></h3>
<h3>server.listen(port[, host][, backlog][, callback])<span><a class="mark" href="#https_server_listen_port_host_backlog_callback" id="https_server_listen_port_host_backlog_callback">#</a></span></h3>
<p>See <a href="http.html#http_server_listen_port_hostname_backlog_callback"><code>http.listen()</code></a> for details.</p>
<h2>https.get(options, callback)<span><a class="mark" href="#https_https_get_options_callback" id="https_https_get_options_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.6</span>
</div><p>Like <a href="http.html#http_http_get_options_callback"><code>http.get()</code></a> but for HTTPS.</p>
<p><code>options</code> can be an object or a string. If <code>options</code> is a string, it is
automatically parsed with <a href="url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost"><code>url.parse()</code></a>.</p>
<p>Example:</p>
<pre><code class="lang-js">const https = require('https');
https.get('https://encrypted.google.com/', (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
}).on('error', (e) => {
console.error(e);
});
</code></pre>
<h2>https.globalAgent<span><a class="mark" href="#https_https_globalagent" id="https_https_globalagent">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.9</span>
</div><p>Global instance of <a href="#https_class_https_agent"><code>https.Agent</code></a> for all HTTPS client requests.</p>
<h2>https.request(options, callback)<span><a class="mark" href="#https_https_request_options_callback" id="https_https_request_options_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.6</span>
</div><p>Makes a request to a secure web server.</p>
<p><code>options</code> can be an object or a string. If <code>options</code> is a string, it is
automatically parsed with <a href="url.html#url_url_parse_urlstr_parsequerystring_slashesdenotehost"><code>url.parse()</code></a>.</p>
<p>All options from <a href="http.html#http_http_request_options_callback"><code>http.request()</code></a> are valid.</p>
<p>Example:</p>
<pre><code class="lang-js">const https = require('https');
var options = {
hostname: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET'
};
var req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.on('data', (d) => {
process.stdout.write(d);
});
});
req.on('error', (e) => {
console.error(e);
});
req.end();
</code></pre>
<p>The options argument has the following options</p>
<ul>
<li><code>host</code>: A domain name or IP address of the server to issue the request to.
Defaults to <code>'localhost'</code>.</li>
<li><code>hostname</code>: Alias for <code>host</code>. To support <code>url.parse()</code> <code>hostname</code> is
preferred over <code>host</code>.</li>
<li><code>family</code>: IP address family to use when resolving <code>host</code> and <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>port</code>: Port of remote server. Defaults to 443.</li>
<li><code>localAddress</code>: Local interface to bind for network connections.</li>
<li><code>socketPath</code>: Unix Domain Socket (use one of host:port or socketPath).</li>
<li><code>method</code>: A string specifying the HTTP request method. Defaults to <code>'GET'</code>.</li>
<li><code>path</code>: Request path. Defaults to <code>'/'</code>. 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>headers</code>: An object containing request headers.</li>
<li><code>auth</code>: Basic authentication i.e. <code>'user:password'</code> to compute an
Authorization header.</li>
<li><code>agent</code>: Controls <a href="#https_class_https_agent"><code>Agent</code></a> behavior. When an Agent is used request will
default to <code>Connection: keep-alive</code>. Possible values:<ul>
<li><code>undefined</code> (default): use <a href="#https_https_globalagent"><code>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>: opts out of connection pooling with an Agent, defaults request to
<code>Connection: close</code>.</li>
</ul>
</li>
</ul>
<p>The following options from <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a> can also be specified:</p>
<ul>
<li><code>pfx</code>: Certificate, Private key and CA certificates to use for SSL. Default <code>null</code>.</li>
<li><code>key</code>: Private key to use for SSL. Default <code>null</code>.</li>
<li><code>passphrase</code>: A string of passphrase for the private key or pfx. Default <code>null</code>.</li>
<li><code>cert</code>: Public x509 certificate to use. Default <code>null</code>.</li>
<li><code>ca</code>: A string, <a href="buffer.html#buffer_buffer"><code>Buffer</code></a> or array of strings or <a href="buffer.html#buffer_buffer"><code>Buffer</code></a>s of trusted
certificates in PEM format. If this is omitted several well known "root"
CAs will be used, like VeriSign. These are used to authorize connections.</li>
<li><code>ciphers</code>: A string describing the ciphers to use or exclude. Consult
<a href="https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT">https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT</a> for
details on the format.</li>
<li><code>rejectUnauthorized</code>: If <code>true</code>, the server certificate is verified against
the list of supplied CAs. An <code>'error'</code> event is emitted if verification
fails. Verification happens at the connection level, <em>before</em> the HTTP
request is sent. Default <code>true</code>.</li>
<li><code>secureProtocol</code>: The SSL method to use, e.g. <code>SSLv3_method</code> to force
SSL version 3. The possible values depend on your installation of
OpenSSL and are defined in the constant <a href="https://www.openssl.org/docs/ssl/ssl.html#DEALING-WITH-PROTOCOL-METHODS"><code>SSL_METHODS</code></a>.</li>
<li><code>servername</code>: Servername for SNI (Server Name Indication) TLS extension.</li>
</ul>
<p>In order to specify these options, use a custom <a href="#https_class_https_agent"><code>Agent</code></a>.</p>
<p>Example:</p>
<pre><code class="lang-js">var options = {
hostname: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET',
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
options.agent = new https.Agent(options);
var req = https.request(options, (res) => {
...
}
</code></pre>
<p>Alternatively, opt out of connection pooling by not using an <code>Agent</code>.</p>
<p>Example:</p>
<pre><code class="lang-js">var options = {
hostname: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET',
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
agent: false
};
var req = https.request(options, (res) => {
...
}
</code></pre>
<!-- [end-include:https.md] -->
<!-- [start-include:modules.md] -->
<h1>Modules<span><a class="mark" href="#modules_modules" id="modules_modules">#</a></span></h1>
<pre class="api_stability api_stability_3">Stability: 3 - Locked</pre><!--name=module-->
<p>Node.js has a simple module loading system. In Node.js, files and modules
are in one-to-one correspondence (each file is treated as a separate module).</p>
<p>As an example, consider a file named <code>foo.js</code>:</p>
<pre><code class="lang-js">const circle = require('./circle.js');
console.log(`The area of a circle of radius 4 is ${circle.area(4)}`);
</code></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="lang-js">const PI = Math.PI;
exports.area = (r) => PI * r * r;
exports.circumference = (r) => 2 * PI * r;
</code></pre>
<p>The module <code>circle.js</code> has exported the functions <code>area()</code> and
<code>circumference()</code>. To add functions and objects to the root of your module,
you can add them to 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="#modules_the_module_wrapper">module wrapper</a>).
In this example, the variable <code>PI</code> is private to <code>circle.js</code>.</p>
<p>If you want the root of your module's export to be a function (such as a
constructor) or if you want to export a complete object in one assignment
instead of building it one property at a time, assign it to <code>module.exports</code>
instead of <code>exports</code>.</p>
<p>Below, <code>bar.js</code> makes use of the <code>square</code> module, which exports a constructor:</p>
<pre><code class="lang-js">const square = require('./square.js');
var mySquare = square(2);
console.log(`The area of my square is ${mySquare.area()}`);
</code></pre>
<p>The <code>square</code> module is defined in <code>square.js</code>:</p>
<pre><code class="lang-js">// assigning to exports will not modify module, must use module.exports
module.exports = (width) => {
return {
area: () => width * width
};
}
</code></pre>
<p>The module system is implemented in the <code>require("module")</code> module.</p>
<h2>Accessing the main module<span><a class="mark" href="#modules_accessing_the_main_module" id="modules_accessing_the_main_module">#</a></span></h2>
<!-- type=misc -->
<p>When a file is run directly from Node.js, <code>require.main</code> is set to its
<code>module</code>. That means that you can determine whether a file has been run
directly by testing</p>
<pre><code class="lang-js">require.main === module
</code></pre>
<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>Because <code>module</code> provides a <code>filename</code> property (normally equivalent to
<code>__filename</code>), the entry point of the current application can be obtained
by checking <code>require.main.filename</code>.</p>
<h2>Addenda: Package Manager Tips<span><a class="mark" href="#modules_addenda_package_manager_tips" id="modules_addenda_package_manager_tips">#</a></span></h2>
<!-- type=misc -->
<p>The semantics of Node.js's <code>require()</code> function were designed to be general
enough to support a number of 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>Below 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>, you
may have to install a specific version of package <code>bar</code>. The <code>bar</code> package
may itself have dependencies, and in some cases, these dependencies may even
collide or form cycles.</p>
<p>Since Node.js looks up the <code>realpath</code> of any modules it loads (that is,
resolves symlinks), and then looks for their dependencies in the <code>node_modules</code>
folders as described <a href="#modules_loading_from_node_modules_folders">here</a>, this
situation is very simple to resolve 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>
<h2>All Together...<span><a class="mark" href="#modules_all_together" id="modules_all_together">#</a></span></h2>
<!-- type=misc -->
<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 require.resolve does:</p>
<pre><code>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 './' or '/' or '../'
a. LOAD_AS_FILE(Y + X)
b. LOAD_AS_DIRECTORY(Y + X)
3. LOAD_NODE_MODULES(X, dirname(Y))
4. THROW "not found"
LOAD_AS_FILE(X)
1. If X is a file, load X as JavaScript text. STOP
2. If X.js is a file, load X.js as JavaScript text. STOP
3. If X.json is a file, parse X.json to a JavaScript Object. STOP
4. If X.node is a file, load X.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. let M = X + (json main field)
c. LOAD_AS_FILE(M)
2. If X/index.js is a file, load X/index.js as JavaScript text. STOP
3. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
4. If X/index.node is a file, load X/index.node as binary addon. STOP
LOAD_NODE_MODULES(X, START)
1. let DIRS=NODE_MODULES_PATHS(START)
2. for each DIR in DIRS:
a. LOAD_AS_FILE(DIR/X)
b. 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" CONTINUE
b. DIR = path join(PARTS[0 .. I] + "node_modules")
c. DIRS = DIRS + DIR
d. let I = I - 1
5. return DIRS
</code></pre><h2>Caching<span><a class="mark" href="#modules_caching" id="modules_caching">#</a></span></h2>
<!--type=misc-->
<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>Multiple calls to <code>require('foo')</code> may 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>If you want to have a module execute code multiple times, then export a
function, and call that function.</p>
<h3>Module Caching Caveats<span><a class="mark" href="#modules_module_caching_caveats" id="modules_module_caching_caveats">#</a></span></h3>
<!--type=misc-->
<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>
<h2>Core Modules<span><a class="mark" href="#modules_core_modules" id="modules_core_modules">#</a></span></h2>
<!--type=misc-->
<p>Node.js has several modules compiled into the binary. These modules are
described in greater detail elsewhere in this documentation.</p>
<p>The core modules are defined within Node.js's source and are located in the
<code>lib/</code> folder.</p>
<p>Core 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.</p>
<h2>Cycles<span><a class="mark" href="#modules_cycles" id="modules_cycles">#</a></span></h2>
<!--type=misc-->
<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>console.log('a starting');
exports.done = false;
const b = require('./b.js');
console.log('in a, b.done = %j', b.done);
exports.done = true;
console.log('a done');
</code></pre><p><code>b.js</code>:</p>
<pre><code>console.log('b starting');
exports.done = false;
const a = require('./a.js');
console.log('in b, a.done = %j', a.done);
exports.done = true;
console.log('b done');
</code></pre><p><code>main.js</code>:</p>
<pre><code>console.log('main starting');
const a = require('./a.js');
const b = require('./b.js');
console.log('in main, a.done=%j, b.done=%j', a.done, b.done);
</code></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>$ node main.js
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></pre><p>If you have cyclic module dependencies in your program, make sure to
plan accordingly.</p>
<h2>File Modules<span><a class="mark" href="#modules_file_modules" id="modules_file_modules">#</a></span></h2>
<!--type=misc-->
<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>.</p>
<p><code>.js</code> files are interpreted as JavaScript text files, and <code>.json</code> files are
parsed as JSON text files. <code>.node</code> files are interpreted as compiled addon
modules loaded with <code>dlopen</code>.</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 '/', './', or '../' 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 an <a href="errors.html#errors_class_error"><code>Error</code></a> with its
<code>code</code> property set to <code>'MODULE_NOT_FOUND'</code>.</p>
<h2>Folders as Modules<span><a class="mark" href="#modules_folders_as_modules" id="modules_folders_as_modules">#</a></span></h2>
<!--type=misc-->
<p>It is convenient to organize programs and libraries into self-contained
directories, and then provide a single entry point to that library.
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 <code>package.json</code> file in the root of the folder,
which specifies a <code>main</code> module. An example package.json file might
look like this:</p>
<pre><code>{ "name" : "some-library",
"main" : "./lib/some-library.js" }
</code></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>This is the extent of Node.js's awareness of package.json files.</p>
<p>Note: If the file specified by the <code>"main"</code> entry of <code>package.json</code> is missing
and can not be resolved, Node.js will report the entire module as missing with
the default error:</p>
<pre><code>Error: Cannot find module 'some-library'
</code></pre><p>If there is no package.json file present in the directory, 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 package.json file in the above
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>
<h2>Loading from <code>node_modules</code> Folders<span><a class="mark" href="#modules_loading_from_node_modules_folders" id="modules_loading_from_node_modules_folders">#</a></span></h2>
<!--type=misc-->
<p>If the module identifier passed to <code>require()</code> is not a
<a href="#modules_core_modules">core</a> module, and does not begin with <code>'/'</code>, <code>'../'</code>, or
<code>'./'</code>, then Node.js starts at the parent directory of the current module, and
adds <code>/node_modules</code>, and attempts to load the module from that location. Node
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>You can 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>
<h2>Loading from the global folders<span><a class="mark" href="#modules_loading_from_the_global_folders" id="modules_loading_from_the_global_folders">#</a></span></h2>
<!-- type=misc -->
<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. (Note: On Windows, <code>NODE_PATH</code> is delimited by
semicolons instead of colons.)</p>
<p><code>NODE_PATH</code> was originally created to support loading modules from
varying paths before the current <a href="#modules_all_together">module resolution</a> algorithm was frozen.</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 locations:</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 Node.js's
configured <code>node_prefix</code>.</p>
<p>These are mostly for historic reasons. <strong>You are highly encouraged
to place your dependencies locally in <code>node_modules</code> folders.</strong> They
will be loaded faster, and more reliably.</p>
<h2>The module wrapper<span><a class="mark" href="#modules_the_module_wrapper" id="modules_the_module_wrapper">#</a></span></h2>
<!-- type=misc -->
<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="lang-js">(function (exports, require, module, __filename, __dirname) {
// Your module code actually lives in here
});
</code></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>
<h2>The <code>module</code> Object<span><a class="mark" href="#modules_the_module_object" id="modules_the_module_object">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div><!-- type=var -->
<!-- name=module -->
<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> isn't actually
a global but rather local to each module.</p>
<h3>module.children<span><a class="mark" href="#modules_module_children" id="modules_module_children">#</a></span></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/Array" class="type"><Array></a></li>
</ul>
<p>The module objects required by this one.</p>
<h3>module.exports<span><a class="mark" href="#modules_module_exports" id="modules_module_exports">#</a></span></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>The <code>module.exports</code> object is created by the Module 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>. Note that assigning
the desired object to <code>exports</code> will simply rebind the local <code>exports</code> variable,
which is probably not what you want to do.</p>
<p>For example suppose we were making a module called <code>a.js</code></p>
<pre><code class="lang-js">const EventEmitter = require('events');
module.exports = new EventEmitter();
// Do some work, and after some time emit
// the 'ready' event from the module itself.
setTimeout(() => {
module.exports.emit('ready');
}, 1000);
</code></pre>
<p>Then in another file we could do</p>
<pre><code class="lang-js">const a = require('./a');
a.on('ready', () => {
console.log('module a is ready');
});
</code></pre>
<p>Note that assignment to <code>module.exports</code> must be done immediately. It cannot be
done in any callbacks. This does not work:</p>
<p>x.js:</p>
<pre><code class="lang-js">setTimeout(() => {
module.exports = { a: 'hello' };
}, 0);
</code></pre>
<p>y.js:</p>
<pre><code class="lang-js">const x = require('./x');
console.log(x.a);
</code></pre>
<h4>exports shortcut<span><a class="mark" href="#modules_exports_shortcut" id="modules_exports_shortcut">#</a></span></h4>
<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="lang-js">module.exports.hello = true; // Exported from require of module
exports = { hello: false }; // Not exported, only available in the module
</code></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>, for example:</p>
<pre><code class="lang-js">module.exports = exports = function Constructor() {
// ... etc.
</code></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="lang-js">function require(...) {
var module = { exports: {} };
((module, exports) => {
// Your module code here. In this example, define a function.
function some_func() {};
exports = some_func;
// At this point, exports is no longer a shortcut to module.exports, and
// this module will still export an empty default object.
module.exports = some_func;
// At this point, the module will now export some_func, instead of the
// default object.
})(module, module.exports);
return module.exports;
}
</code></pre>
<h3>module.filename<span><a class="mark" href="#modules_module_filename" id="modules_module_filename">#</a></span></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 fully resolved filename to the module.</p>
<h3>module.id<span><a class="mark" href="#modules_module_id" id="modules_module_id">#</a></span></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 identifier for the module. Typically this is the fully resolved
filename.</p>
<h3>module.loaded<span><a class="mark" href="#modules_module_loaded" id="modules_module_loaded">#</a></span></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#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>
<h3>module.parent<span><a class="mark" href="#modules_module_parent" id="modules_module_parent">#</a></span></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> Module object</li>
</ul>
<p>The module that first required this one.</p>
<h3>module.require(id)<span><a class="mark" href="#modules_module_require_id" id="modules_module_require_id">#</a></span></h3>
<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/Reference/Global_Objects/Object" class="type"><Object></a> <code>module.exports</code> from the resolved module</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>Note that in order to do this, you must 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>
<!-- [end-include:modules.md] -->
<!-- [start-include:net.md] -->
<h1>Net<span><a class="mark" href="#net_net" id="net_net">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>The <code>net</code> module provides you with an asynchronous network wrapper. It contains
functions for creating both servers and clients (called streams). You can include
this module with <code>require('net');</code>.</p>
<h2>Class: net.Server<span><a class="mark" href="#net_class_net_server" id="net_class_net_server">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>This class is used to create a TCP or local server.</p>
<p><code>net.Server</code> is an <a href="events.html#events_class_eventemitter"><code>EventEmitter</code></a> with the following events:</p>
<h3>Event: 'close'<span><a class="mark" href="#net_event_close" id="net_event_close">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div><p>Emitted when the server closes. Note that if connections exist, this
event is not emitted until all connections are ended.</p>
<h3>Event: 'connection'<span><a class="mark" href="#net_event_connection" id="net_event_connection">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><ul>
<li><a href="net.html#net_class_net_socket" 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>
<h3>Event: 'error'<span><a class="mark" href="#net_event_error" id="net_event_error">#</a></span></h3>
<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="net.html#net_class_net_socket"><code>net.Socket</code></a>, the <a href="#net_event_close"><code>'close'</code></a>
event will <strong>not</strong> be emitted directly following this event unless
<a href="#net_server_close_callback"><code>server.close()</code></a> is manually called. See the example in discussion of
<a href="#net_server_listen_port_hostname_backlog_callback"><code>server.listen()</code></a>.</p>
<h3>Event: 'listening'<span><a class="mark" href="#net_event_listening" id="net_event_listening">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>Emitted when the server has been bound after calling <code>server.listen</code>.</p>
<h3>server.address()<span><a class="mark" href="#net_server_address" id="net_server_address">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>Returns the bound address, the address family name, and port of the server
as reported by the operating system.
Useful to find which port was assigned when getting an OS-assigned address.
Returns an object with <code>port</code>, <code>family</code>, and <code>address</code> properties:
<code>{ port: 12346, family: 'IPv4', address: '127.0.0.1' }</code></p>
<p>Example:</p>
<pre><code class="lang-js">var server = net.createServer((socket) => {
socket.end('goodbye\n');
}).on('error', (err) => {
// handle errors here
throw err;
});
// grab a random port.
server.listen(() => {
console.log('opened server on', server.address());
});
</code></pre>
<p>Don't call <code>server.address()</code> until the <code>'listening'</code> event has been emitted.</p>
<h3>server.close([callback])<span><a class="mark" href="#net_server_close_callback" id="net_server_close_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><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="#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 Error as its only argument if the server
was not open when it was closed.</p>
<h3>server.connections<span><a class="mark" href="#net_server_connections" id="net_server_connections">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.2.0</span>
<span>Deprecated since: v0.9.7 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated: Use <a href="#net_server_getconnections_callback"><code>server.getConnections()</code></a> instead.</pre><p>The number of concurrent connections on the server.</p>
<p>This becomes <code>null</code> when sending a socket to a child with
<a href="child_process.html#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>. To poll forks and get current number of active
connections use asynchronous <code>server.getConnections</code> instead.</p>
<h3>server.getConnections(callback)<span><a class="mark" href="#net_server_getconnections_callback" id="net_server_getconnections_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.7</span>
</div><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>
<h3>server.listen(handle[, backlog][, callback])<span><a class="mark" href="#net_server_listen_handle_backlog_callback" id="net_server_listen_handle_backlog_callback">#</a></span></h3>
<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></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>The <code>handle</code> object can be set to either a server or socket (anything
with an underlying <code>_handle</code> member), or a <code>{fd: <n>}</code> object.</p>
<p>This will cause the server to accept connections on the specified
handle, but it is presumed that the file descriptor or handle has
already been bound to a port or domain socket.</p>
<p>Listening on a file descriptor is not supported on Windows.</p>
<p>This function is asynchronous. When the server has been bound,
<a href="#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="#net_event_listening"><code>'listening'</code></a> event.</p>
<p>The parameter <code>backlog</code> behaves the same as in
<a href="#net_server_listen_port_hostname_backlog_callback"><code>server.listen([port][, hostname][, backlog][, callback])</code></a>.</p>
<h3>server.listen(options[, callback])<span><a class="mark" href="#net_server_listen_options_callback" id="net_server_listen_options_callback">#</a></span></h3>
<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"><Number></a> - Optional.</li>
<li><code>host</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> - Optional.</li>
<li><code>backlog</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type" class="type"><Number></a> - Optional.</li>
<li><code>path</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> - Optional.</li>
<li><code>exclusive</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> - Optional.</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> - Optional.</li>
</ul>
<p>The <code>port</code>, <code>host</code>, and <code>backlog</code> properties of <code>options</code>, as well as the
optional callback function, behave as they do on a call to
<a href="#net_server_listen_port_hostname_backlog_callback"><code>server.listen([port][, hostname][, backlog][, callback])</code></a>.
Alternatively, the <code>path</code> option can be used to specify a UNIX socket.</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="lang-js">server.listen({
host: 'localhost',
port: 80,
exclusive: true
});
</code></pre>
<h3>server.listen(path[, backlog][, callback])<span><a class="mark" href="#net_server_listen_path_backlog_callback" id="net_server_listen_path_backlog_callback">#</a></span></h3>
<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>backlog</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>Start a local socket server listening for connections on the given <code>path</code>.</p>
<p>This function is asynchronous. When the server has been bound,
<a href="#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="#net_event_listening"><code>'listening'</code></a> event.</p>
<p>On UNIX, the local domain is usually known as the UNIX domain. The path is a
filesystem path name. It gets truncated to <code>sizeof(sockaddr_un.sun_path)</code>
bytes, decreased by 1. It varies on different operating system between 91 and
107 bytes. The typical values are 107 on Linux and 103 on OS X. The path is
subject to the same naming conventions and permissions checks as would be done
on file creation, will be visible in the filesystem, and will <em>persist until
unlinked</em>.</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 appearances, the pipe name space is flat. Pipes will <em>not
persist</em>, they are removed when the last reference to them is closed. Do not
forget JavaScript string escaping requires paths to be specified with
double-backslashes, such as:</p>
<pre><code>net.createServer().listen(
path.join('\\\\?\\pipe', process.cwd(), 'myctl'))
</code></pre><p>The parameter <code>backlog</code> behaves the same as in
<a href="#net_server_listen_port_hostname_backlog_callback"><code>server.listen([port][, hostname][, backlog][, callback])</code></a>.</p>
<h3>server.listen([port][, hostname][, backlog][, callback])<span><a class="mark" href="#net_server_listen_port_hostname_backlog_callback" id="net_server_listen_port_hostname_backlog_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>Begin accepting connections on the specified <code>port</code> and <code>hostname</code>. If the
<code>hostname</code> is omitted, the server will accept connections on any IPv6 address
(<code>::</code>) when IPv6 is available, or any IPv4 address (<code>0.0.0.0</code>) otherwise.
Omit the port argument, or use a port value of <code>0</code>, to have the operating system
assign a random port, which can be retrieved by using <code>server.address().port</code>
after the <code>'listening'</code> event has been emitted.</p>
<p>Backlog is 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>This function is asynchronous. When the server has been bound,
<a href="#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="#net_event_listening"><code>'listening'</code></a> event.</p>
<p>One issue some users run into is getting <code>EADDRINUSE</code> errors. This means that
another server is already running on the requested port. One way of handling this
would be to wait a second and then try again:</p>
<pre><code class="lang-js">server.on('error', (e) => {
if (e.code == 'EADDRINUSE') {
console.log('Address in use, retrying...');
setTimeout(() => {
server.close();
server.listen(PORT, HOST);
}, 1000);
}
});
</code></pre>
<p>(Note: All sockets in Node.js are set <code>SO_REUSEADDR</code>.)</p>
<h3>server.maxConnections<span><a class="mark" href="#net_server_maxconnections" id="net_server_maxconnections">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.2.0</span>
</div><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="child_process.html#child_process_child_process_fork_modulepath_args_options"><code>child_process.fork()</code></a>.</p>
<h3>server.ref()<span><a class="mark" href="#net_server_ref" id="net_server_ref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div><p>Opposite of <code>unref</code>, calling <code>ref</code> on a previously <code>unref</code>d 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>d calling <code>ref</code> again will have no effect.</p>
<p>Returns <code>server</code>.</p>
<h3>server.unref()<span><a class="mark" href="#net_server_unref" id="net_server_unref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div><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>d calling
<code>unref</code> again will have no effect.</p>
<p>Returns <code>server</code>.</p>
<h2>Class: net.Socket<span><a class="mark" href="#net_class_net_socket" id="net_class_net_socket">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.4</span>
</div><p>This object is an abstraction of a TCP or local socket. <code>net.Socket</code>
instances implement a duplex Stream interface. They can be created by the
user and used as a client (with <a href="#net_socket_connect_options_connectlistener"><code>connect()</code></a>) or they can be created by Node.js
and passed to the user through the <code>'connection'</code> event of a server.</p>
<h3>new net.Socket(<a href="#zlib_class_options">options</a>)<span><a class="mark" href="#net_new_net_socket_options" id="net_new_net_socket_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.4</span>
</div><p>Construct a new socket object.</p>
<p><code>options</code> is an object with the following defaults:</p>
<pre><code class="lang-js">{
fd: null,
allowHalfOpen: false,
readable: false,
writable: false
}
</code></pre>
<p><code>fd</code> allows you to specify the existing file descriptor of socket.
Set <code>readable</code> and/or <code>writable</code> to <code>true</code> to allow reads and/or writes on this
socket (NOTE: Works only when <code>fd</code> is passed).
About <code>allowHalfOpen</code>, refer to <code>createServer()</code> and <code>'end'</code> event.</p>
<p><code>net.Socket</code> instances are <a href="events.html#events_class_eventemitter"><code>EventEmitter</code></a> with the following events:</p>
<h3>Event: 'close'<span><a class="mark" href="#net_event_close_1" id="net_event_close_1">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><ul>
<li><code>had_error</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>had_error</code> is a boolean
which says if the socket was closed due to a transmission error.</p>
<h3>Event: 'connect'<span><a class="mark" href="#net_event_connect" id="net_event_connect">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>Emitted when a socket connection is successfully established.
See <a href="#net_socket_connect_options_connectlistener"><code>connect()</code></a>.</p>
<h3>Event: 'data'<span><a class="mark" href="#net_event_data" id="net_event_data">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><ul>
<li><a href="buffer.html#buffer_class_buffer" class="type"><Buffer></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 <code>socket.setEncoding()</code>.
(See the <a href="stream.html#stream_class_stream_readable">Readable Stream</a> section for more information.)</p>
<p>Note that the <strong>data will be lost</strong> if there is no listener when a <code>Socket</code>
emits a <code>'data'</code> event.</p>
<h3>Event: 'drain'<span><a class="mark" href="#net_event_drain" id="net_event_drain">#</a></span></h3>
<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>
<h3>Event: 'end'<span><a class="mark" href="#net_event_end" id="net_event_end">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>Emitted when the other end of the socket sends a FIN packet.</p>
<p>By default (<code>allowHalfOpen == false</code>) the socket will destroy its file
descriptor once it has written out its pending write queue. However, by
setting <code>allowHalfOpen == true</code> the socket will not automatically <code>end()</code>
its side allowing the user to write arbitrary amounts of data, with the
caveat that the user is required to <code>end()</code> their side now.</p>
<h3>Event: 'error'<span><a class="mark" href="#net_event_error_1" id="net_event_error_1">#</a></span></h3>
<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>
<h3>Event: 'lookup'<span><a class="mark" href="#net_event_lookup" id="net_event_lookup">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.3</span>
</div><p>Emitted after resolving the hostname 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="dns.html#dns_dns_lookup_hostname_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#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 address type. See <a href="dns.html#dns_dns_lookup_hostname_options_callback"><code>dns.lookup()</code></a>.</li>
</ul>
<h3>Event: 'timeout'<span><a class="mark" href="#net_event_timeout" id="net_event_timeout">#</a></span></h3>
<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="#net_socket_settimeout_timeout_callback"><code>socket.setTimeout()</code></a></p>
<h3>socket.address()<span><a class="mark" href="#net_socket_address" id="net_socket_address">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>Returns the bound address, the address family name and port of the
socket as reported by the operating system. Returns an object with
three properties, e.g.
<code>{ port: 12346, family: 'IPv4', address: '127.0.0.1' }</code></p>
<h3>socket.bufferSize<span><a class="mark" href="#net_socket_buffersize" id="net_socket_buffersize">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.8</span>
</div><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. (Internally it is
polling on the socket's file descriptor for being writable).</p>
<p>The consequence of this internal buffering is that memory may grow. This
property shows the number of characters currently buffered to be written.
(Number of characters is approximately equal to the number of bytes to be
written, but the buffer may contain strings, and the strings are lazily
encoded, so the exact number of bytes is not known.)</p>
<p>Users who experience large or growing <code>bufferSize</code> should attempt to
"throttle" the data flows in their program with <a href="#net_socket_pause"><code>pause()</code></a> and <a href="#net_socket_resume"><code>resume()</code></a>.</p>
<h3>socket.bytesRead<span><a class="mark" href="#net_socket_bytesread" id="net_socket_bytesread">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.3</span>
</div><p>The amount of received bytes.</p>
<h3>socket.bytesWritten<span><a class="mark" href="#net_socket_byteswritten" id="net_socket_byteswritten">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.3</span>
</div><p>The amount of bytes sent.</p>
<h3>socket.connect(options[, connectListener])<span><a class="mark" href="#net_socket_connect_options_connectlistener" id="net_socket_connect_options_connectlistener">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>Opens the connection for a given socket.</p>
<p>For TCP sockets, <code>options</code> argument should be an object which specifies:</p>
<ul>
<li><p><code>port</code>: Port the client should connect to (Required).</p>
</li>
<li><p><code>host</code>: Host the client should connect to. Defaults to <code>'localhost'</code>.</p>
</li>
<li><p><code>localAddress</code>: Local interface to bind to for network connections.</p>
</li>
<li><p><code>localPort</code>: Local port to bind to for network connections.</p>
</li>
<li><p><code>family</code> : Version of IP stack. Defaults to <code>4</code>.</p>
</li>
<li><p><code>lookup</code> : Custom lookup function. Defaults to <code>dns.lookup</code>.</p>
</li>
</ul>
<p>For local domain sockets, <code>options</code> argument should be an object which
specifies:</p>
<ul>
<li><code>path</code>: Path the client should connect to (Required).</li>
</ul>
<p>Normally this method is not needed, as <code>net.createConnection</code> opens the
socket. Use this only if you are implementing a custom Socket.</p>
<p>This function is asynchronous. When the <a href="#net_event_connect"><code>'connect'</code></a> event is emitted the
socket is established. If there is a problem connecting, the <code>'connect'</code> event
will not be emitted, the <a href="#net_event_error_1"><code>'error'</code></a> event will be emitted with the exception.</p>
<p>The <code>connectListener</code> parameter will be added as a listener for the
<a href="#net_event_connect"><code>'connect'</code></a> event.</p>
<h3>socket.connect(path[, connectListener])<span><a class="mark" href="#net_socket_connect_path_connectlistener" id="net_socket_connect_path_connectlistener">#</a></span></h3>
<h3>socket.connect(port[, host][, connectListener])<span><a class="mark" href="#net_socket_connect_port_host_connectlistener" id="net_socket_connect_port_host_connectlistener">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>As <a href="#net_socket_connect_options_connectlistener"><code>socket.connect(options\[, connectListener\])</code></a>,
with options either as either <code>{port: port, host: host}</code> or <code>{path: path}</code>.</p>
<h3>socket.destroy()<span><a class="mark" href="#net_socket_destroy" id="net_socket_destroy">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>Ensures that no more I/O activity happens on this socket. Only necessary in
case of errors (parse error or so).</p>
<h3>socket.destroyed<span><a class="mark" href="#net_socket_destroyed" id="net_socket_destroyed">#</a></span></h3>
<p>A Boolean value that indicates if the connection is destroyed or not. Once a
connection is destroyed no further data can be transferred using it.</p>
<h3>socket.end([data][, encoding])<span><a class="mark" href="#net_socket_end_data_encoding" id="net_socket_end_data_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>Half-closes the socket. i.e., it sends a FIN packet. It is possible the
server will still send some data.</p>
<p>If <code>data</code> is specified, it is equivalent to calling
<code>socket.write(data, encoding)</code> followed by <code>socket.end()</code>.</p>
<h3>socket.localAddress<span><a class="mark" href="#net_socket_localaddress" id="net_socket_localaddress">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.6</span>
</div><p>The string representation of the local IP address the remote client is
connecting on. For example, if you are listening on <code>'0.0.0.0'</code> and the
client connects on <code>'192.168.1.1'</code>, the value would be <code>'192.168.1.1'</code>.</p>
<h3>socket.localPort<span><a class="mark" href="#net_socket_localport" id="net_socket_localport">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.6</span>
</div><p>The numeric representation of the local port. For example,
<code>80</code> or <code>21</code>.</p>
<h3>socket.pause()<span><a class="mark" href="#net_socket_pause" id="net_socket_pause">#</a></span></h3>
<p>Pauses the reading of data. That is, <a href="#stream_event_data"><code>'data'</code></a> events will not be emitted.
Useful to throttle back an upload.</p>
<h3>socket.ref()<span><a class="mark" href="#net_socket_ref" id="net_socket_ref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div><p>Opposite of <code>unref</code>, calling <code>ref</code> on a previously <code>unref</code>d 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>d calling <code>ref</code> again will have no effect.</p>
<p>Returns <code>socket</code>.</p>
<h3>socket.remoteAddress<span><a class="mark" href="#net_socket_remoteaddress" id="net_socket_remoteaddress">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.10</span>
</div><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>
<h3>socket.remoteFamily<span><a class="mark" href="#net_socket_remotefamily" id="net_socket_remotefamily">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div><p>The string representation of the remote IP family. <code>'IPv4'</code> or <code>'IPv6'</code>.</p>
<h3>socket.remotePort<span><a class="mark" href="#net_socket_remoteport" id="net_socket_remoteport">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.10</span>
</div><p>The numeric representation of the remote port. For example,
<code>80</code> or <code>21</code>.</p>
<h3>socket.resume()<span><a class="mark" href="#net_socket_resume" id="net_socket_resume">#</a></span></h3>
<p>Resumes reading after a call to <a href="#net_socket_pause"><code>pause()</code></a>.</p>
<h3>socket.setEncoding([encoding])<span><a class="mark" href="#net_socket_setencoding_encoding" id="net_socket_setencoding_encoding">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>Set the encoding for the socket as a <a href="stream.html#stream_class_stream_readable">Readable Stream</a>. See
<a href="stream.html#stream_readable_setencoding_encoding"><code>stream.setEncoding()</code></a> for more information.</p>
<h3>socket.setKeepAlive([enable][, initialDelay])<span><a class="mark" href="#net_socket_setkeepalive_enable_initialdelay" id="net_socket_setkeepalive_enable_initialdelay">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.92</span>
</div><p>Enable/disable keep-alive functionality, and optionally set the initial
delay before the first keepalive probe is sent on an idle socket.
<code>enable</code> defaults to <code>false</code>.</p>
<p>Set <code>initialDelay</code> (in milliseconds) to set the delay between the last
data packet received and the first keepalive probe. Setting 0 for
initialDelay will leave the value unchanged from the default
(or previous) setting. Defaults to <code>0</code>.</p>
<p>Returns <code>socket</code>.</p>
<h3>socket.setNoDelay([noDelay])<span><a class="mark" href="#net_socket_setnodelay_nodelay" id="net_socket_setnodelay_nodelay">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>Disables the Nagle algorithm. By default TCP connections use the Nagle
algorithm, they buffer data before sending it off. Setting <code>true</code> for
<code>noDelay</code> will immediately fire off data each time <code>socket.write()</code> is called.
<code>noDelay</code> defaults to <code>true</code>.</p>
<p>Returns <code>socket</code>.</p>
<h3>socket.setTimeout(timeout[, callback])<span><a class="mark" href="#net_socket_settimeout_timeout_callback" id="net_socket_settimeout_timeout_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><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="#net_event_timeout"><code>'timeout'</code></a>
event but the connection will not be severed. The user must manually <a href="#net_socket_end_data_encoding"><code>end()</code></a>
or <a href="#net_socket_destroy"><code>destroy()</code></a> the socket.</p>
<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="#net_event_timeout"><code>'timeout'</code></a> event.</p>
<p>Returns <code>socket</code>.</p>
<h3>socket.unref()<span><a class="mark" href="#net_socket_unref" id="net_socket_unref">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div><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>d calling
<code>unref</code> again will have no effect.</p>
<p>Returns <code>socket</code>.</p>
<h3>socket.write(data[, encoding][, callback])<span><a class="mark" href="#net_socket_write_data_encoding_callback" id="net_socket_write_data_encoding_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><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="#stream_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 - this may not be immediately.</p>
<h2>net.connect(options[, connectListener])<span><a class="mark" href="#net_net_connect_options_connectlistener" id="net_net_connect_options_connectlistener">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div><p>A factory function, which returns a new <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> and automatically
connects with the supplied <code>options</code>.</p>
<p>The options are passed to both the <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> constructor and the
<a href="#net_socket_connect_options_connectlistener"><code>socket.connect</code></a> method.</p>
<p>The <code>connectListener</code> parameter will be added as a listener for the
<a href="#net_event_connect"><code>'connect'</code></a> event once.</p>
<p>Here is an example of a client of the previously described echo server:</p>
<pre><code class="lang-js">const net = require('net');
const client = net.connect({port: 8124}, () => {
// 'connect' listener
console.log('connected to server!');
client.write('world!\r\n');
});
client.on('data', (data) => {
console.log(data.toString());
client.end();
});
client.on('end', () => {
console.log('disconnected from server');
});
</code></pre>
<p>To connect on the socket <code>/tmp/echo.sock</code> the second line would just be
changed to</p>
<pre><code class="lang-js">const client = net.connect({path: '/tmp/echo.sock'});
</code></pre>
<h2>net.connect(path[, connectListener])<span><a class="mark" href="#net_net_connect_path_connectlistener" id="net_net_connect_path_connectlistener">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>A factory function, which returns a new unix <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> and automatically
connects to the supplied <code>path</code>.</p>
<p>The <code>connectListener</code> parameter will be added as a listener for the
<a href="#net_event_connect"><code>'connect'</code></a> event once.</p>
<h2>net.connect(port[, host][, connectListener])<span><a class="mark" href="#net_net_connect_port_host_connectlistener" id="net_net_connect_port_host_connectlistener">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>A factory function, which returns a new <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> and automatically
connects to the supplied <code>port</code> and <code>host</code>.</p>
<p>If <code>host</code> is omitted, <code>'localhost'</code> will be assumed.</p>
<p>The <code>connectListener</code> parameter will be added as a listener for the
<a href="#net_event_connect"><code>'connect'</code></a> event once.</p>
<h2>net.createConnection(options[, connectListener])<span><a class="mark" href="#net_net_createconnection_options_connectlistener" id="net_net_createconnection_options_connectlistener">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>A factory function, which returns a new <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> and automatically
connects with the supplied <code>options</code>.</p>
<p>The options are passed to both the <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> constructor and the
<a href="#net_socket_connect_options_connectlistener"><code>socket.connect</code></a> method.</p>
<p>The <code>connectListener</code> parameter will be added as a listener for the
<a href="#net_event_connect"><code>'connect'</code></a> event once.</p>
<p>Here is an example of a client of the previously described echo server:</p>
<pre><code class="lang-js">const net = require('net');
const client = net.createConnection({port: 8124}, () => {
//'connect' listener
console.log('connected to server!');
client.write('world!\r\n');
});
client.on('data', (data) => {
console.log(data.toString());
client.end();
});
client.on('end', () => {
console.log('disconnected from server');
});
</code></pre>
<p>To connect on the socket <code>/tmp/echo.sock</code> the second line would just be
changed to</p>
<pre><code class="lang-js">const client = net.connect({path: '/tmp/echo.sock'});
</code></pre>
<h2>net.createConnection(path[, connectListener])<span><a class="mark" href="#net_net_createconnection_path_connectlistener" id="net_net_createconnection_path_connectlistener">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>A factory function, which returns a new unix <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> and automatically
connects to the supplied <code>path</code>.</p>
<p>The <code>connectListener</code> parameter will be added as a listener for the
<a href="#net_event_connect"><code>'connect'</code></a> event once.</p>
<h2>net.createConnection(port[, host][, connectListener])<span><a class="mark" href="#net_net_createconnection_port_host_connectlistener" id="net_net_createconnection_port_host_connectlistener">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.90</span>
</div><p>A factory function, which returns a new <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> and automatically
connects to the supplied <code>port</code> and <code>host</code>.</p>
<p>If <code>host</code> is omitted, <code>'localhost'</code> will be assumed.</p>
<p>The <code>connectListener</code> parameter will be added as a listener for the
<a href="#net_event_connect"><code>'connect'</code></a> event once.</p>
<h2>net.createServer([options][, connectionListener])<span><a class="mark" href="#net_net_createserver_options_connectionlistener" id="net_net_createserver_options_connectionlistener">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div><p>Creates a new server. The <code>connectionListener</code> argument is
automatically set as a listener for the <a href="#net_event_connection"><code>'connection'</code></a> event.</p>
<p><code>options</code> is an object with the following defaults:</p>
<pre><code class="lang-js">{
allowHalfOpen: false,
pauseOnConnect: false
}
</code></pre>
<p>If <code>allowHalfOpen</code> is <code>true</code>, then the socket won't automatically send a FIN
packet when the other end of the socket sends a FIN packet. The socket becomes
non-readable, but still writable. You should call the <a href="#net_socket_end_data_encoding"><code>end()</code></a> method explicitly.
See <a href="#stream_event_end"><code>'end'</code></a> event for more information.</p>
<p>If <code>pauseOnConnect</code> is <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="#net_socket_resume"><code>resume()</code></a>.</p>
<p>Here is an example of an echo server which listens for connections
on port 8124:</p>
<pre><code class="lang-js">const net = require('net');
const server = net.createServer((c) => {
// 'connection' listener
console.log('client connected');
c.on('end', () => {
console.log('client disconnected');
});
c.write('hello\r\n');
c.pipe(c);
});
server.on('error', (err) => {
throw err;
});
server.listen(8124, () => {
console.log('server bound');
});
</code></pre>
<p>Test this by using <code>telnet</code>:</p>
<pre><code>telnet localhost 8124
</code></pre><p>To listen on the socket <code>/tmp/echo.sock</code> the third line from the last would
just be changed to</p>
<pre><code class="lang-js">server.listen('/tmp/echo.sock', () => {
console.log('server bound');
});
</code></pre>
<p>Use <code>nc</code> to connect to a UNIX domain socket server:</p>
<pre><code class="lang-js">nc -U /tmp/echo.sock
</code></pre>
<h2>net.isIP(input)<span><a class="mark" href="#net_net_isip_input" id="net_net_isip_input">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div><p>Tests if input is an IP address. Returns 0 for invalid strings,
returns 4 for IP version 4 addresses, and returns 6 for IP version 6 addresses.</p>
<h2>net.isIPv4(input)<span><a class="mark" href="#net_net_isipv4_input" id="net_net_isipv4_input">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div><p>Returns true if input is a version 4 IP address, otherwise returns false.</p>
<h2>net.isIPv6(input)<span><a class="mark" href="#net_net_isipv6_input" id="net_net_isipv6_input">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div><p>Returns true if input is a version 6 IP address, otherwise returns false.</p>
<!-- [end-include:net.md] -->
<!-- [start-include:os.md] -->
<h1>OS<span><a class="mark" href="#os_os" id="os_os">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>Provides a few basic operating-system related utility functions.</p>
<p>Use <code>require('os')</code> to access this module.</p>
<h2>os.EOL<span><a class="mark" href="#os_os_eol" id="os_os_eol">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.8</span>
</div><p>A constant defining the appropriate End-of-line marker for the operating
system.</p>
<h2>os.arch()<span><a class="mark" href="#os_os_arch" id="os_os_arch">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div><p>Returns the operating system CPU architecture. Possible values are <code>'x64'</code>,
<code>'arm'</code> and <code>'ia32'</code>. Returns the value of <a href="process.html#process_process_arch"><code>process.arch</code></a>.</p>
<h2>os.cpus()<span><a class="mark" href="#os_os_cpus" id="os_os_cpus">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.3</span>
</div><p>Returns an array of objects containing information about each CPU/core
installed: model, speed (in MHz), and times (an object containing the number of
milliseconds the CPU/core spent in: user, nice, sys, idle, and irq).</p>
<p>Example inspection of os.cpus:</p>
<pre><code class="lang-js">[ { model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times:
{ user: 252020,
nice: 0,
sys: 30340,
idle: 1070356870,
irq: 0 } },
{ model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times:
{ user: 306960,
nice: 0,
sys: 26980,
idle: 1071569080,
irq: 0 } },
{ model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times:
{ user: 248450,
nice: 0,
sys: 21750,
idle: 1070919370,
irq: 0 } },
{ model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times:
{ user: 256880,
nice: 0,
sys: 19430,
idle: 1070905480,
irq: 20 } },
{ model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times:
{ user: 511580,
nice: 20,
sys: 40900,
idle: 1070842510,
irq: 0 } },
{ model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times:
{ user: 291660,
nice: 0,
sys: 34360,
idle: 1070888000,
irq: 10 } },
{ model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times:
{ user: 308260,
nice: 0,
sys: 55410,
idle: 1071129970,
irq: 880 } },
{ model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz',
speed: 2926,
times:
{ user: 266450,
nice: 1480,
sys: 34920,
idle: 1072572010,
irq: 30 } } ]
</code></pre>
<p>Note that since <code>nice</code> values are UNIX centric in Windows the <code>nice</code> values of
all processors are always 0.</p>
<h2>os.endianness()<span><a class="mark" href="#os_os_endianness" id="os_os_endianness">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div><p>Returns the endianness of the CPU. Possible values are <code>'BE'</code> for big endian
or <code>'LE'</code> for little endian.</p>
<h2>os.freemem()<span><a class="mark" href="#os_os_freemem" id="os_os_freemem">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.3</span>
</div><p>Returns the amount of free system memory in bytes.</p>
<h2>os.homedir()<span><a class="mark" href="#os_os_homedir" id="os_os_homedir">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v2.3.0</span>
</div><p>Returns the home directory of the current user.</p>
<h2>os.hostname()<span><a class="mark" href="#os_os_hostname" id="os_os_hostname">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.3</span>
</div><p>Returns the hostname of the operating system.</p>
<h2>os.loadavg()<span><a class="mark" href="#os_os_loadavg" id="os_os_loadavg">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.3</span>
</div><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. As a rule of thumb, the load
average should ideally be less than the number of logical CPUs in the system.</p>
<p>The load average is a very UNIX-y concept; there is no real equivalent on
Windows platforms. That is why this function always returns <code>[0, 0, 0]</code> on
Windows.</p>
<h2>os.networkInterfaces()<span><a class="mark" href="#os_os_networkinterfaces" id="os_os_networkinterfaces">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.6.0</span>
</div><p>Get a list of network interfaces:</p>
<pre><code class="lang-js">{ lo:
[ { address: '127.0.0.1',
netmask: '255.0.0.0',
family: 'IPv4',
mac: '00:00:00:00:00:00',
internal: true },
{ address: '::1',
netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
family: 'IPv6',
mac: '00:00:00:00:00:00',
internal: true } ],
eth0:
[ { address: '192.168.1.108',
netmask: '255.255.255.0',
family: 'IPv4',
mac: '01:02:03:0a:0b:0c',
internal: false },
{ address: 'fe80::a00:27ff:fe4e:66a1',
netmask: 'ffff:ffff:ffff:ffff::',
family: 'IPv6',
mac: '01:02:03:0a:0b:0c',
internal: false } ] }
</code></pre>
<p>Note that due to the underlying implementation this will only return network
interfaces that have been assigned an address.</p>
<h2>os.platform()<span><a class="mark" href="#os_os_platform" id="os_os_platform">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div><p>Returns the operating system platform. Possible values are <code>'darwin'</code>,
<code>'freebsd'</code>, <code>'linux'</code>, <code>'sunos'</code> or <code>'win32'</code>. Returns the value of
<a href="process.html#process_process_platform"><code>process.platform</code></a>.</p>
<h2>os.release()<span><a class="mark" href="#os_os_release" id="os_os_release">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.3</span>
</div><p>Returns the operating system release.</p>
<h2>os.tmpdir()<span><a class="mark" href="#os_os_tmpdir" id="os_os_tmpdir">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.9.9</span>
</div><p>Returns the operating system's default directory for temporary files.</p>
<h2>os.totalmem()<span><a class="mark" href="#os_os_totalmem" id="os_os_totalmem">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.3</span>
</div><p>Returns the total amount of system memory in bytes.</p>
<h2>os.type()<span><a class="mark" href="#os_os_type" id="os_os_type">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.3</span>
</div><p>Returns the operating system name. For example <code>'Linux'</code> on Linux, <code>'Darwin'</code>
on OS X and <code>'Windows_NT'</code> on Windows.</p>
<h2>os.uptime()<span><a class="mark" href="#os_os_uptime" id="os_os_uptime">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.3</span>
</div><p>Returns the system uptime in seconds.</p>
<!-- [end-include:os.md] -->
<!-- [start-include:path.md] -->
<h1>Path<span><a class="mark" href="#path_path" id="path_path">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>This module contains utilities for handling and transforming file
paths. Almost all these methods perform only string transformations.
The file system is not consulted to check whether paths are valid.</p>
<p>Use <code>require('path')</code> to use this module. The following methods are provided:</p>
<h2>path.basename(p[, ext])<span><a class="mark" href="#path_path_basename_p_ext" id="path_path_basename_p_ext">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.25</span>
</div><p>Return the last portion of a path. Similar to the Unix <code>basename</code> command.</p>
<p>Example:</p>
<pre><code class="lang-js">path.basename('/foo/bar/baz/asdf/quux.html')
// returns 'quux.html'
path.basename('/foo/bar/baz/asdf/quux.html', '.html')
// returns 'quux'
</code></pre>
<h2>path.delimiter<span><a class="mark" href="#path_path_delimiter" id="path_path_delimiter">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.9.3</span>
</div><p>The platform-specific path delimiter, <code>;</code> or <code>':'</code>.</p>
<p>An example on *nix:</p>
<pre><code class="lang-js">console.log(process.env.PATH)
// '/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin'
process.env.PATH.split(path.delimiter)
// returns ['/usr/bin', '/bin', '/usr/sbin', '/sbin', '/usr/local/bin']
</code></pre>
<p>An example on Windows:</p>
<pre><code class="lang-js">console.log(process.env.PATH)
// 'C:\Windows\system32;C:\Windows;C:\Program Files\node\'
process.env.PATH.split(path.delimiter)
// returns ['C:\\Windows\\system32', 'C:\\Windows', 'C:\\Program Files\\node\\']
</code></pre>
<h2>path.dirname(p)<span><a class="mark" href="#path_path_dirname_p" id="path_path_dirname_p">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div><p>Return the directory name of a path. Similar to the Unix <code>dirname</code> command.</p>
<p>Example:</p>
<pre><code class="lang-js">path.dirname('/foo/bar/baz/asdf/quux')
// returns '/foo/bar/baz/asdf'
</code></pre>
<h2>path.extname(p)<span><a class="mark" href="#path_path_extname_p" id="path_path_extname_p">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.25</span>
</div><p>Return the extension of the path, from the last '.' to end of string
in the last portion of the path. If there is no '.' in the last portion
of the path or the first character of it is '.', then it returns
an empty string. Examples:</p>
<pre><code class="lang-js">path.extname('index.html')
// returns '.html'
path.extname('index.coffee.md')
// returns '.md'
path.extname('index.')
// returns '.'
path.extname('index')
// returns ''
path.extname('.index')
// returns ''
</code></pre>
<h2>path.format(pathObject)<span><a class="mark" href="#path_path_format_pathobject" id="path_path_format_pathobject">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.15</span>
</div><p>Returns a path string from an object, the opposite of <a href="#path_path_parse_pathstring"><code>path.parse</code></a>.</p>
<p>Examples:</p>
<p>Some Posix system examples:</p>
<pre><code class="lang-js">// If `dir` and `base` are provided, `dir` + platform separator + `base`
// will be returned.
path.format({
dir: '/home/user/dir',
base: 'file.txt'
});
// returns '/home/user/dir/file.txt'
// `base` will be returned if `dir` or `root` are not provided.
path.format({
base: 'file.txt'
});
// returns 'file.txt'
</code></pre>
<h2>path.isAbsolute(path)<span><a class="mark" href="#path_path_isabsolute_path" id="path_path_isabsolute_path">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.2</span>
</div><p>Determines whether <code>path</code> is an absolute path. An absolute path will always
resolve to the same location, regardless of the working directory.</p>
<p>Posix examples:</p>
<pre><code class="lang-js">path.isAbsolute('/foo/bar') // true
path.isAbsolute('/baz/..') // true
path.isAbsolute('qux/') // false
path.isAbsolute('.') // false
</code></pre>
<p>Windows examples:</p>
<pre><code class="lang-js">path.isAbsolute('//server') // true
path.isAbsolute('C:/foo/..') // true
path.isAbsolute('bar\\baz') // false
path.isAbsolute('.') // false
</code></pre>
<p><em>Note:</em> If the path string passed as parameter is a zero-length string, unlike
other path module functions, it will be used as-is and <code>false</code> will be
returned.</p>
<h2>path.join([path1][, path2][, ...])<span><a class="mark" href="#path_path_join_path1_path2" id="path_path_join_path1_path2">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div><p>Join all arguments together and normalize the resulting path.</p>
<p>Arguments must be strings. In v0.8, non-string arguments were
silently ignored. In v0.10 and up, an exception is thrown.</p>
<p>Example:</p>
<pre><code class="lang-js">path.join('/foo', 'bar', 'baz/asdf', 'quux', '..')
// returns '/foo/bar/baz/asdf'
path.join('foo', {}, 'bar')
// throws exception
TypeError: Arguments to path.join must be strings
</code></pre>
<p><em>Note:</em> If the arguments to <code>join</code> have zero-length strings, unlike other path
module functions, they will be ignored. If the joined path string is a
zero-length string then <code>'.'</code> will be returned, which represents the
current working directory.</p>
<h2>path.normalize(p)<span><a class="mark" href="#path_path_normalize_p" id="path_path_normalize_p">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.23</span>
</div><p>Normalize a string path, taking care of <code>'..'</code> and <code>'.'</code> parts.</p>
<p>When multiple slashes are found, they're replaced by a single one;
when the path contains a trailing slash, it is preserved.
On Windows backslashes are used.</p>
<p>Example:</p>
<pre><code class="lang-js">path.normalize('/foo/bar//baz/asdf/quux/..')
// returns '/foo/bar/baz/asdf'
</code></pre>
<p><em>Note:</em> If the path string passed as argument is a zero-length string then <code>'.'</code>
will be returned, which represents the current working directory.</p>
<h2>path.parse(pathString)<span><a class="mark" href="#path_path_parse_pathstring" id="path_path_parse_pathstring">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.15</span>
</div><p>Returns an object from a path string.</p>
<p>An example on *nix:</p>
<pre><code class="lang-js">path.parse('/home/user/dir/file.txt')
// returns
// {
// root : "/",
// dir : "/home/user/dir",
// base : "file.txt",
// ext : ".txt",
// name : "file"
// }
</code></pre>
<p>An example on Windows:</p>
<pre><code class="lang-js">path.parse('C:\\path\\dir\\index.html')
// returns
// {
// root : "C:\\",
// dir : "C:\\path\\dir",
// base : "index.html",
// ext : ".html",
// name : "index"
// }
</code></pre>
<h2>path.posix<span><a class="mark" href="#path_path_posix" id="path_path_posix">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.15</span>
</div><p>Provide access to aforementioned <code>path</code> methods but always interact in a posix
compatible way.</p>
<h2>path.relative(from, to)<span><a class="mark" href="#path_path_relative_from_to" id="path_path_relative_from_to">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div><p>Solve the relative path from <code>from</code> to <code>to</code>.</p>
<p>At times we have two absolute paths, and we need to derive the relative
path from one to the other. This is actually the reverse transform of
<code>path.resolve</code>, which means we see that:</p>
<pre><code class="lang-js">path.resolve(from, path.relative(from, to)) == path.resolve(to)
</code></pre>
<p>Examples:</p>
<pre><code class="lang-js">path.relative('C:\\orandea\\test\\aaa', 'C:\\orandea\\impl\\bbb')
// returns '..\\..\\impl\\bbb'
path.relative('/data/orandea/test/aaa', '/data/orandea/impl/bbb')
// returns '../../impl/bbb'
</code></pre>
<p><em>Note:</em> If the arguments to <code>relative</code> have zero-length strings then the current
working directory will be used instead of the zero-length strings. If
both the paths are the same then a zero-length string will be returned.</p>
<h2>path.resolve([from ...], to)<span><a class="mark" href="#path_path_resolve_from_to" id="path_path_resolve_from_to">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.4</span>
</div><p>Resolves <code>to</code> to an absolute path.</p>
<p>If <code>to</code> isn't already absolute <code>from</code> arguments are prepended in right to left
order, until an absolute path is found. If after using all <code>from</code> paths still
no absolute path is found, the current working directory is used as well. The
resulting path is normalized, and trailing slashes are removed unless the path
gets resolved to the root directory. Non-string <code>from</code> arguments are ignored.</p>
<p>Another way to think of it is as a sequence of <code>cd</code> commands in a shell.</p>
<pre><code class="lang-js">path.resolve('foo/bar', '/tmp/file/', '..', 'a/../subfile')
</code></pre>
<p>Is similar to:</p>
<pre><code>cd foo/bar
cd /tmp/file/
cd ..
cd a/../subfile
pwd
</code></pre><p>The difference is that the different paths don't need to exist and may also be
files.</p>
<p>Examples:</p>
<pre><code class="lang-js">path.resolve('/foo/bar', './baz')
// returns '/foo/bar/baz'
path.resolve('/foo/bar', '/tmp/file/')
// returns '/tmp/file'
path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif')
// if currently in /home/myself/node, it returns
// '/home/myself/node/wwwroot/static_files/gif/image.gif'
</code></pre>
<p><em>Note:</em> If the arguments to <code>resolve</code> have zero-length strings then the current
working directory will be used instead of them.</p>
<h2>path.sep<span><a class="mark" href="#path_path_sep" id="path_path_sep">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.9</span>
</div><p>The platform-specific file separator. <code>'\\'</code> or <code>'/'</code>.</p>
<p>An example on *nix:</p>
<pre><code class="lang-js">'foo/bar/baz'.split(path.sep)
// returns ['foo', 'bar', 'baz']
</code></pre>
<p>An example on Windows:</p>
<pre><code class="lang-js">'foo\\bar\\baz'.split(path.sep)
// returns ['foo', 'bar', 'baz']
</code></pre>
<h2>path.win32<span><a class="mark" href="#path_path_win32" id="path_path_win32">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.15</span>
</div><p>Provide access to aforementioned <code>path</code> methods but always interact in a win32
compatible way.</p>
<!-- [end-include:path.md] -->
<!-- [start-include:process.md] -->
<h1>Process<span><a class="mark" href="#process_process" id="process_process">#</a></span></h1>
<!-- type=global -->
<p>The <code>process</code> object is a global object and can be accessed from anywhere.
It is an instance of <a href="events.html#events_class_eventemitter"><code>EventEmitter</code></a>.</p>
<h2>Event: 'beforeExit'<span><a class="mark" href="#process_event_beforeexit" id="process_event_beforeexit">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.12</span>
</div><p>This event is emitted when Node.js empties its event loop and has nothing else
to schedule. Normally, Node.js exits when there is no work scheduled, but a
listener for <code>'beforeExit'</code> can make asynchronous calls, and cause Node.js to
continue.</p>
<p><code>'beforeExit'</code> is not emitted for conditions causing explicit termination, such
as <a href="#process_process_exit_code"><code>process.exit()</code></a> or uncaught exceptions, and should not be used as an
alternative to the <code>'exit'</code> event unless the intention is to schedule more work.</p>
<h2>Event: 'exit'<span><a class="mark" href="#process_event_exit" id="process_event_exit">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.7</span>
</div><p>Emitted when the process is about to exit. 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 process will exit. Therefore you <strong>must</strong> only perform
<strong>synchronous</strong> operations in this handler. This is a good hook to perform
checks on the module's state (like for unit tests). The callback takes one
argument, the code the process is exiting with.</p>
<p>This event is only emitted when Node.js exits explicitly by process.exit() or
implicitly by the event loop draining.</p>
<p>Example of listening for <code>'exit'</code>:</p>
<pre><code class="lang-js">process.on('exit', (code) => {
// do *NOT* do this
setTimeout(() => {
console.log('This will not run');
}, 0);
console.log('About to exit with code:', code);
});
</code></pre>
<h2>Event: 'message'<span><a class="mark" href="#process_event_message" id="process_event_message">#</a></span></h2>
<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 parsed JSON object or primitive value</li>
<li><code>sendHandle</code> <span class="type"><Handle object></span> a <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> or <a href="net.html#net_class_net_server"><code>net.Server</code></a> object, or
undefined.</li>
</ul>
<p>Messages sent by <a href="child_process.html#child_process_child_send_message_sendhandle_callback"><code>ChildProcess.send()</code></a> are obtained using the <code>'message'</code>
event on the child's process object.</p>
<h2>Event: 'rejectionHandled'<span><a class="mark" href="#process_event_rejectionhandled" id="process_event_rejectionhandled">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v1.4.1</span>
</div><p>Emitted whenever a Promise was rejected and an error handler was attached to it
(for example with <code>.catch()</code>) later than after an event loop turn. This event
is emitted with the following arguments:</p>
<ul>
<li><code>p</code> the promise that was previously emitted in an <code>'unhandledRejection'</code>
event, but which has now gained a rejection handler.</li>
</ul>
<p>There is no notion of a top level for a promise chain at which rejections can
always be handled. Being inherently asynchronous in nature, a promise 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 is a
growing-and-shrinking list of unhandled rejections. In synchronous code, the
<code>'uncaughtException'</code> event tells you when the list of unhandled exceptions
grows. And in asynchronous code, the <code>'unhandledRejection'</code> event tells you
when the list of unhandled rejections grows, while the <code>'rejectionHandled'</code>
event tells you when the list of unhandled rejections shrinks.</p>
<p>For example using the rejection detection hooks in order to keep a map of all
the rejected promise reasons at a given time:</p>
<pre><code class="lang-js">const unhandledRejections = new Map();
process.on('unhandledRejection', (reason, p) => {
unhandledRejections.set(p, reason);
});
process.on('rejectionHandled', (p) => {
unhandledRejections.delete(p);
});
</code></pre>
<p>This map will grow and shrink over time, reflecting rejections that start
unhandled and then become handled. You could record the errors in some error
log, either periodically (probably best for long-running programs, allowing
you to clear the map, which in the case of a very buggy program could grow
indefinitely) or upon process exit (more convenient for scripts).</p>
<h2>Event: 'uncaughtException'<span><a class="mark" href="#process_event_uncaughtexception" id="process_event_uncaughtexception">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.18</span>
</div><p>The <code>'uncaughtException'</code> event is emitted when an exception bubbles all the
way back to the event loop. By default, Node.js handles such exceptions by
printing the stack trace to stderr and exiting. Adding a handler for the
<code>'uncaughtException'</code> event overrides this default behavior.</p>
<p>For example:</p>
<pre><code class="lang-js">process.on('uncaughtException', (err) => {
console.log(`Caught exception: ${err}`);
});
setTimeout(() => {
console.log('This will still run.');
}, 500);
// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
console.log('This will not run.');
</code></pre>
<h3>Warning: Using <code>'uncaughtException'</code> correctly<span><a class="mark" href="#process_warning_using_uncaughtexception_correctly" id="process_warning_using_uncaughtexception_correctly">#</a></span></h3>
<p>Note that <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 of the power cord when upgrading a computer -- nine out of ten
times nothing happens - but the 10th 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. It is not safe to resume normal operation after
<code>'uncaughtException'</code>.</p>
<h2>Event: 'unhandledRejection'<span><a class="mark" href="#process_event_unhandledrejection" id="process_event_unhandledrejection">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v1.4.1</span>
</div><p>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. Such promises 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 rejections are propagated through
a promise chain. This event is useful for detecting and keeping track of
promises that were rejected whose rejections were not handled yet. This event
is emitted with the following arguments:</p>
<ul>
<li><code>reason</code> the object with which the promise was rejected (usually an
<a href="errors.html#errors_class_error"><code>Error</code></a> instance).</li>
<li><code>p</code> the promise that was rejected.</li>
</ul>
<p>Here is an example that logs every unhandled rejection to the console</p>
<pre><code class="lang-js">process.on('unhandledRejection', (reason, p) => {
console.log('Unhandled Rejection at: Promise', p, 'reason:', reason);
// application specific logging, throwing an error, or other logic here
});
</code></pre>
<p>For example, here is a rejection that will trigger the <code>'unhandledRejection'</code>
event:</p>
<pre><code class="lang-js">somePromise.then((res) => {
return reportToUser(JSON.pasre(res)); // note the typo (`pasre`)
}); // no `.catch` or `.then`
</code></pre>
<p>Here is an example of a coding pattern that will also trigger
<code>'unhandledRejection'</code>:</p>
<pre><code class="lang-js">function SomeResource() {
// Initially set the loaded status to a rejected promise
this.loaded = Promise.reject(new Error('Resource not yet loaded!'));
}
var resource = new SomeResource();
// no .catch or .then on resource.loaded for at least a turn
</code></pre>
<p>In cases like this, you may not want to track the rejection as a developer
error like you would for other <code>'unhandledRejection'</code> events. To address
this, you can either attach a dummy <code>.catch(() => { })</code> handler to
<code>resource.loaded</code>, preventing the <code>'unhandledRejection'</code> event from being
emitted, or you can use the <a href="#process_event_rejectionhandled"><code>'rejectionHandled'</code></a> event.</p>
<h2>Exit Codes<span><a class="mark" href="#process_exit_codes" id="process_exit_codes">#</a></span></h2>
<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 <code>'uncaughtException'</code> 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 Node.js's 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 Node.js's 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 a <code>process.on('uncaughtException')</code> 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 Node.js's 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>--debug</code> and/or <code>--debug-brk</code>
options were set, but an invalid port number was chosen.</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 Unix 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.</li>
</ul>
<h2>Signal Events<span><a class="mark" href="#process_signal_events" id="process_signal_events">#</a></span></h2>
<!--type=event-->
<!--name=SIGINT, SIGHUP, etc.-->
<p>Emitted when the processes receives a signal. See <a href="http://man7.org/linux/man-pages/man7/sigaction.7.html">sigaction(7)</a> for a list of
standard POSIX signal names such as <code>SIGINT</code>, <code>SIGHUP</code>, etc.</p>
<p>Example of listening for <code>SIGINT</code>:</p>
<pre><code class="lang-js">// Start reading from stdin so we don't exit.
process.stdin.resume();
process.on('SIGINT', () => {
console.log('Got SIGINT. Press Control-D to exit.');
});
</code></pre>
<p>An easy way to send the <code>SIGINT</code> signal is with <code>Control-C</code> in most terminal
programs.</p>
<p>Note:</p>
<ul>
<li><code>SIGUSR1</code> is reserved by Node.js to start the debugger. It's possible to
install a listener but that won't stop the debugger from starting.</li>
<li><code>SIGTERM</code> and <code>SIGINT</code> have default handlers on non-Windows platforms that
resets 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">signal(7)</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 <code>CTRL+C</code> (though this may be configurable). It is not generated
when terminal raw mode is enabled.</li>
<li><code>SIGBREAK</code> is delivered on Windows when <code>CTRL+BREAK</code> 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>
</ul>
<p>Note that Windows does not support sending Signals, but Node.js offers some
emulation with <code>process.kill()</code>, and <code>child_process.kill()</code>. Sending signal <code>0</code>
can be used to test for the existence of a process. Sending <code>SIGINT</code>,
<code>SIGTERM</code>, and <code>SIGKILL</code> cause the unconditional termination of the target
process.</p>
<h2>process.abort()<span><a class="mark" href="#process_process_abort" id="process_process_abort">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div><p>This causes Node.js to emit an abort. This will cause Node.js to exit and
generate a core file.</p>
<h2>process.arch<span><a class="mark" href="#process_process_arch" id="process_process_arch">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div><p>What processor architecture you're running on: <code>'arm'</code>, <code>'ia32'</code>, or <code>'x64'</code>.</p>
<pre><code class="lang-js">console.log('This processor architecture is ' + process.arch);
</code></pre>
<h2>process.argv<span><a class="mark" href="#process_process_argv" id="process_process_argv">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.27</span>
</div><p>An array containing the command line arguments. The first element will be
'node', the second element will be the name of the JavaScript file. The
next elements will be any additional command line arguments.</p>
<pre><code class="lang-js">// print process.argv
process.argv.forEach((val, index, array) => {
console.log(`${index}: ${val}`);
});
</code></pre>
<p>This will generate:</p>
<pre><code>$ node process-2.js one two=three four
0: node
1: /Users/mjr/work/node/process-2.js
2: one
3: two=three
4: four
</code></pre><h2>process.chdir(directory)<span><a class="mark" href="#process_process_chdir_directory" id="process_process_chdir_directory">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.17</span>
</div><p>Changes the current working directory of the process or throws an exception if that fails.</p>
<pre><code class="lang-js">console.log(`Starting directory: ${process.cwd()}`);
try {
process.chdir('/tmp');
console.log(`New directory: ${process.cwd()}`);
}
catch (err) {
console.log(`chdir: ${err}`);
}
</code></pre>
<h2>process.config<span><a class="mark" href="#process_process_config" id="process_process_config">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div><p>An Object containing the JavaScript representation of the configure options
that were 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>
<pre><code>{
target_defaults:
{ cflags: [],
default_configuration: 'Release',
defines: [],
include_dirs: [],
libraries: [] },
variables:
{
host_arch: 'x64',
node_install_npm: 'true',
node_prefix: '',
node_shared_cares: 'false',
node_shared_http_parser: 'false',
node_shared_libuv: 'false',
node_shared_zlib: 'false',
node_use_dtrace: 'false',
node_use_openssl: 'true',
node_shared_openssl: 'false',
strict_aliasing: 'true',
target_arch: 'x64',
v8_use_snapshot: 'true'
}
}
</code></pre><p><em>Note: the <code>process.config</code> property is <strong>not</strong> read-only and there are existing
modules in the ecosystem that are known to extend, modify, or entirely replace
the value of <code>process.config</code>.</em></p>
<h2>process.connected<span><a class="mark" href="#process_process_connected" id="process_process_connected">#</a></span></h2>
<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 false after <code>process.disconnect()</code> is called</li>
</ul>
<p>If <code>process.connected</code> is false, it is no longer possible to send messages.</p>
<h2>process.cpuUsage([previousValue])<span><a class="mark" href="#process_process_cpuusage_previousvalue" id="process_process_cpuusage_previousvalue">#</a></span></h2>
<p>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><code class="lang-js">const startUsage = process.cpuUsage();
// { user: 38579, system: 6986 }
// spin the CPU for 500 milliseconds
const now = Date.now();
while (Date.now() - now < 500);
console.log(process.cpuUsage(startUsage));
// { user: 514883, system: 11226 }
</code></pre>
<h2>process.cwd()<span><a class="mark" href="#process_process_cwd" id="process_process_cwd">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.8</span>
</div><p>Returns the current working directory of the process.</p>
<pre><code class="lang-js">console.log(`Current directory: ${process.cwd()}`);
</code></pre>
<h2>process.disconnect()<span><a class="mark" href="#process_process_disconnect" id="process_process_disconnect">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.2</span>
</div><p>Close the IPC channel to the parent process, allowing this child to exit
gracefully once there are no other connections keeping it alive.</p>
<p>Identical to the parent process's <a href="child_process.html#child_process_child_disconnect"><code>ChildProcess.disconnect()</code></a>.</p>
<p>If Node.js was not spawned with an IPC channel, <code>process.disconnect()</code> will be
undefined.</p>
<h2>process.env<span><a class="mark" href="#process_process_env" id="process_process_env">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.27</span>
</div><p>An object containing the user environment. See <a href="http://man7.org/linux/man-pages/man7/environ.7.html">environ(7)</a>.</p>
<p>An example of this object looks like:</p>
<pre><code class="lang-js">{ TERM: 'xterm-256color',
SHELL: '/usr/local/bin/bash',
USER: 'maciej',
PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin',
PWD: '/Users/maciej',
EDITOR: 'vim',
SHLVL: '1',
HOME: '/Users/maciej',
LOGNAME: 'maciej',
_: '/usr/local/bin/node' }
</code></pre>
<p>You can write to this object, but changes won't be reflected outside of your
process. That means that the following won't work:</p>
<pre><code>$ node -e 'process.env.foo = "bar"' && echo $foo
</code></pre><p>But this will:</p>
<pre><code class="lang-js">process.env.foo = 'bar';
console.log(process.env.foo);
</code></pre>
<p>Assigning a property on <code>process.env</code> will implicitly convert the value
to a string.</p>
<p>Example:</p>
<pre><code class="lang-js">process.env.test = null;
console.log(process.env.test);
// => 'null'
process.env.test = undefined;
console.log(process.env.test);
// => 'undefined'
</code></pre>
<p>Use <code>delete</code> to delete a property from <code>process.env</code>.</p>
<p>Example:</p>
<pre><code class="lang-js">process.env.TEST = 1;
delete process.env.TEST;
console.log(process.env.TEST);
// => undefined
</code></pre>
<h2>process.execArgv<span><a class="mark" href="#process_process_execargv" id="process_process_execargv">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div><p>This is the set of Node.js-specific command line options from the
executable that started the process. These options do not show up in
<code>process.argv</code>, 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>
<p>Example:</p>
<pre><code>$ node --harmony script.js --version
</code></pre><p>results in process.execArgv:</p>
<pre><code class="lang-js">['--harmony']
</code></pre>
<p>and process.argv:</p>
<pre><code class="lang-js">['/usr/local/bin/node', 'script.js', '--version']
</code></pre>
<h2>process.execPath<span><a class="mark" href="#process_process_execpath" id="process_process_execpath">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.100</span>
</div><p>This is the absolute pathname of the executable that started the process.</p>
<p>Example:</p>
<pre><code>/usr/local/bin/node
</code></pre><h2>process.exit([code])<span><a class="mark" href="#process_process_exit_code" id="process_process_exit_code">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.13</span>
</div><p>Ends the process with the specified <code>code</code>. If omitted, exit uses the
'success' code <code>0</code>.</p>
<p>To exit with a 'failure' code:</p>
<pre><code class="lang-js">process.exit(1);
</code></pre>
<p>The shell that executed Node.js should see the exit code as 1.</p>
<h2>process.exitCode<span><a class="mark" href="#process_process_exitcode" id="process_process_exitcode">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.8</span>
</div><p>A number which will be the process exit code, when the process either
exits gracefully, or is exited via <a href="#process_process_exit_code"><code>process.exit()</code></a> without specifying
a code.</p>
<p>Specifying a code to <code>process.exit(code)</code> will override any previous
setting of <code>process.exitCode</code>.</p>
<h2>process.getegid()<span><a class="mark" href="#process_process_getegid" id="process_process_getegid">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v2.0.0</span>
</div><p>Note: this function is only available on POSIX platforms (i.e. not Windows,
Android)</p>
<p>Gets the effective group identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/getegid.2.html">getegid(2)</a>.)
This is the numerical group id, not the group name.</p>
<pre><code class="lang-js">if (process.getegid) {
console.log(`Current gid: ${process.getegid()}`);
}
</code></pre>
<h2>process.geteuid()<span><a class="mark" href="#process_process_geteuid" id="process_process_geteuid">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v2.0.0</span>
</div><p>Note: this function is only available on POSIX platforms (i.e. not Windows,
Android)</p>
<p>Gets the effective user identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/geteuid.2.html">geteuid(2)</a>.)
This is the numerical userid, not the username.</p>
<pre><code class="lang-js">if (process.geteuid) {
console.log(`Current uid: ${process.geteuid()}`);
}
</code></pre>
<h2>process.getgid()<span><a class="mark" href="#process_process_getgid" id="process_process_getgid">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.31</span>
</div><p>Note: this function is only available on POSIX platforms (i.e. not Windows,
Android)</p>
<p>Gets the group identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/getgid.2.html">getgid(2)</a>.)
This is the numerical group id, not the group name.</p>
<pre><code class="lang-js">if (process.getgid) {
console.log(`Current gid: ${process.getgid()}`);
}
</code></pre>
<h2>process.getgroups()<span><a class="mark" href="#process_process_getgroups" id="process_process_getgroups">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div><p>Note: this function is only available on POSIX platforms (i.e. not Windows,
Android)</p>
<p>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>
<h2>process.getuid()<span><a class="mark" href="#process_process_getuid" id="process_process_getuid">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.28</span>
</div><p>Note: this function is only available on POSIX platforms (i.e. not Windows,
Android)</p>
<p>Gets the user identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/getuid.2.html">getuid(2)</a>.)
This is the numerical userid, not the username.</p>
<pre><code class="lang-js">if (process.getuid) {
console.log(`Current uid: ${process.getuid()}`);
}
</code></pre>
<h2>process.hrtime()<span><a class="mark" href="#process_process_hrtime" id="process_process_hrtime">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.6</span>
</div><p>Returns the current high-resolution real time in a <code>[seconds, nanoseconds]</code>
tuple Array. It is relative to an arbitrary time in the past. It is not
related to the time of day and therefore not subject to clock drift. The
primary use is for measuring performance between intervals.</p>
<p>You may pass in the result of a previous call to <code>process.hrtime()</code> to get
a diff reading, useful for benchmarks and measuring intervals:</p>
<pre><code class="lang-js">var time = process.hrtime();
// [ 1800216, 25 ]
setTimeout(() => {
var diff = process.hrtime(time);
// [ 1, 552 ]
console.log('benchmark took %d nanoseconds', diff[0] * 1e9 + diff[1]);
// benchmark took 1000000527 nanoseconds
}, 1000);
</code></pre>
<h2>process.initgroups(user, extra_group)<span><a class="mark" href="#process_process_initgroups_user_extra_group" id="process_process_initgroups_user_extra_group">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div><p>Note: this function is only available on POSIX platforms (i.e. not Windows,
Android)</p>
<p>Reads /etc/group and initializes the group access list, using all groups of
which the user is a member. This is a privileged operation, meaning you need
to be root or have the <code>CAP_SETGID</code> capability.</p>
<p><code>user</code> is a user name or user ID. <code>extra_group</code> is a group name or group ID.</p>
<p>Some care needs to be taken when dropping privileges. Example:</p>
<pre><code class="lang-js">console.log(process.getgroups()); // [ 0 ]
process.initgroups('bnoordhuis', 1000); // switch user
console.log(process.getgroups()); // [ 27, 30, 46, 1000, 0 ]
process.setgid(1000); // drop root gid
console.log(process.getgroups()); // [ 27, 30, 46, 1000 ]
</code></pre>
<h2>process.kill(pid[, signal])<span><a class="mark" href="#process_process_kill_pid_signal" id="process_process_kill_pid_signal">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.6</span>
</div><p>Send a signal to a process. <code>pid</code> is the process id and <code>signal</code> is the
string describing the signal to send. Signal names are strings like
<code>SIGINT</code> or <code>SIGHUP</code>. If omitted, the signal will be <code>SIGTERM</code>.
See <a href="#process_signal_events">Signal Events</a> and <a href="http://man7.org/linux/man-pages/man2/kill.2.html">kill(2)</a> for more information.</p>
<p>Will throw an error if target does not exist, and 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>Note that 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>
<p>Example of sending a signal to yourself:</p>
<pre><code class="lang-js">process.on('SIGHUP', () => {
console.log('Got SIGHUP signal.');
});
setTimeout(() => {
console.log('Exiting.');
process.exit(0);
}, 100);
process.kill(process.pid, 'SIGHUP');
</code></pre>
<p>Note: When SIGUSR1 is received by Node.js it starts the debugger, see
<a href="#process_signal_events">Signal Events</a>.</p>
<h2>process.mainModule<span><a class="mark" href="#process_process_mainmodule" id="process_process_mainmodule">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.17</span>
</div><p>Alternate way to retrieve <a href="modules.html#modules_accessing_the_main_module"><code>require.main</code></a>. The difference is that if the main
module changes at runtime, <code>require.main</code> might 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 <code>require.main</code>, it will be <code>undefined</code> if there was no entry script.</p>
<h2>process.memoryUsage()<span><a class="mark" href="#process_process_memoryusage" id="process_process_memoryusage">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.16</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>rss</code> <span class="type"><Integer></span></li>
<li><code>heapTotal</code> <span class="type"><Integer></span></li>
<li><code>heapUsed</code> <span class="type"><Integer></span></li>
<li><code>external</code> <span class="type"><Integer></span></li>
</ul>
</li>
</ul>
<p>The <code>process.memoryUsage()</code> method returns an object describing the memory usage
of the Node.js process measured in bytes.</p>
<p>For example, the code:</p>
<pre><code class="lang-js">console.log(process.memoryUsage());
</code></pre>
<p>This will generate:</p>
<pre><code class="lang-js">{ rss: 4935680,
heapTotal: 1826816,
heapUsed: 650472,
external: 49879
}
</code></pre>
<p><code>heapTotal</code> and <code>heapUsed</code> refer to V8's memory usage.
<code>external</code> refers to the memory usage of C++ objects bound to JavaScript
objects managed by V8.</p>
<h2>process.nextTick(callback[, arg][, ...])<span><a class="mark" href="#process_process_nexttick_callback_arg" id="process_process_nexttick_callback_arg">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.26</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>Once the current event loop turn runs to completion, call the callback
function.</p>
<p>This is <em>not</em> a simple alias to <a href="timers.html#timers_settimeout_callback_delay_arg"><code>setTimeout(fn, 0)</code></a>, it's much more
efficient. It runs before any additional I/O events (including
timers) fire in subsequent ticks of the event loop.</p>
<pre><code class="lang-js">console.log('start');
process.nextTick(() => {
console.log('nextTick callback');
});
console.log('scheduled');
// Output:
// start
// scheduled
// nextTick callback
</code></pre>
<p>This is important in developing APIs where you want to give the user the
chance to assign event handlers after an object has been constructed,
but before any I/O has occurred.</p>
<pre><code class="lang-js">function MyThing(options) {
this.setupOptions(options);
process.nextTick(() => {
this.startDoingStuff();
});
}
var thing = new MyThing();
thing.getReadyForStuff();
// thing.startDoingStuff() gets called now, not before.
</code></pre>
<p>It is very important for APIs to be either 100% synchronous or 100%
asynchronous. Consider this example:</p>
<pre><code class="lang-js">// WARNING! DO NOT USE! BAD UNSAFE HAZARD!
function maybeSync(arg, cb) {
if (arg) {
cb();
return;
}
fs.stat('file', cb);
}
</code></pre>
<p>This API is hazardous. If you do this:</p>
<pre><code class="lang-js">maybeSync(true, () => {
foo();
});
bar();
</code></pre>
<p>then it's not clear whether <code>foo()</code> or <code>bar()</code> will be called first.</p>
<p>This approach is much better:</p>
<pre><code class="lang-js">function definitelyAsync(arg, cb) {
if (arg) {
process.nextTick(cb);
return;
}
fs.stat('file', cb);
}
</code></pre>
<p>Note: the nextTick queue is completely drained on each pass of the
event loop <strong>before</strong> additional I/O is processed. As a result,
recursively setting nextTick callbacks will block any I/O from
happening, just like a <code>while(true);</code> loop.</p>
<h2>process.pid<span><a class="mark" href="#process_process_pid" id="process_process_pid">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.15</span>
</div><p>The PID of the process.</p>
<pre><code class="lang-js">console.log(`This process is pid ${process.pid}`);
</code></pre>
<h2>process.platform<span><a class="mark" href="#process_process_platform" id="process_process_platform">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.16</span>
</div><p>What platform you're running on:
<code>'darwin'</code>, <code>'freebsd'</code>, <code>'linux'</code>, <code>'sunos'</code> or <code>'win32'</code></p>
<pre><code class="lang-js">console.log(`This platform is ${process.platform}`);
</code></pre>
<h2>process.release<span><a class="mark" href="#process_process_release" id="process_process_release">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v3.0.0</span>
</div><p>An Object 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 string with a value that will always be <code>'node'</code> for Node.js. For
legacy io.js releases, this will be <code>'io.js'</code>.</li>
<li><code>sourceUrl</code>: a complete URL pointing to a <em>.tar.gz</em> file containing the
source of the current release.</li>
<li><code>headersUrl</code>: a complete URL pointing to a <em>.tar.gz</em> file containing only
the header files for the current release. This file is significantly smaller
than the full source file and can be used for compiling add-ons against
Node.js.</li>
<li><code>libUrl</code>: a complete URL pointing to an <em>node.lib</em> file matching the
architecture and version of the current release. This file is used for
compiling add-ons against Node.js. <em>This property is only present on Windows
builds of Node.js and will be missing on all other platforms.</em></li>
</ul>
<p>e.g.</p>
<pre><code class="lang-js">{ name: 'node',
sourceUrl: 'https://nodejs.org/download/release/v4.0.0/node-v4.0.0.tar.gz',
headersUrl: 'https://nodejs.org/download/release/v4.0.0/node-v4.0.0-headers.tar.gz',
libUrl: 'https://nodejs.org/download/release/v4.0.0/win-x64/node.lib' }
</code></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>
<h2>process.send(message[, sendHandle][, callback])<span><a class="mark" href="#process_process_send_message_sendhandle_callback" id="process_process_send_message_sendhandle_callback">#</a></span></h2>
<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> <span class="type"><Handle object></span></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 Node.js is spawned with an IPC channel attached, it can send messages to its
parent process using <code>process.send()</code>. Each will be received as a
<a href="child_process.html#child_process_event_message"><code>'message'</code></a> event on the parent's <code>ChildProcess</code> object.</p>
<p><em>Note: this function uses <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify"><code>JSON.stringify()</code></a> internally to serialize the <code>message</code>.</em></p>
<p>If Node.js was not spawned with an IPC channel, <code>process.send()</code> will be undefined.</p>
<h2>process.setegid(id)<span><a class="mark" href="#process_process_setegid_id" id="process_process_setegid_id">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v2.0.0</span>
</div><p>Note: this function is only available on POSIX platforms (i.e. not Windows,
Android)</p>
<p>Sets the effective group identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setegid.2.html">setegid(2)</a>.)
This accepts either a numerical ID or a groupname string. If a groupname
is specified, this method blocks while resolving it to a numerical ID.</p>
<pre><code class="lang-js">if (process.getegid && process.setegid) {
console.log(`Current gid: ${process.getegid()}`);
try {
process.setegid(501);
console.log(`New gid: ${process.getegid()}`);
}
catch (err) {
console.log(`Failed to set gid: ${err}`);
}
}
</code></pre>
<h2>process.seteuid(id)<span><a class="mark" href="#process_process_seteuid_id" id="process_process_seteuid_id">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v2.0.0</span>
</div><p>Note: this function is only available on POSIX platforms (i.e. not Windows,
Android)</p>
<p>Sets the effective user identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/seteuid.2.html">seteuid(2)</a>.)
This accepts either a numerical ID or a username string. If a username
is specified, this method blocks while resolving it to a numerical ID.</p>
<pre><code class="lang-js">if (process.geteuid && process.seteuid) {
console.log(`Current uid: ${process.geteuid()}`);
try {
process.seteuid(501);
console.log(`New uid: ${process.geteuid()}`);
}
catch (err) {
console.log(`Failed to set uid: ${err}`);
}
}
</code></pre>
<h2>process.setgid(id)<span><a class="mark" href="#process_process_setgid_id" id="process_process_setgid_id">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.31</span>
</div><p>Note: this function is only available on POSIX platforms (i.e. not Windows,
Android)</p>
<p>Sets the group identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setgid.2.html">setgid(2)</a>.) This accepts either
a numerical ID or a groupname string. If a groupname is specified, this method
blocks while resolving it to a numerical ID.</p>
<pre><code class="lang-js">if (process.getgid && process.setgid) {
console.log(`Current gid: ${process.getgid()}`);
try {
process.setgid(501);
console.log(`New gid: ${process.getgid()}`);
}
catch (err) {
console.log(`Failed to set gid: ${err}`);
}
}
</code></pre>
<h2>process.setgroups(groups)<span><a class="mark" href="#process_process_setgroups_groups" id="process_process_setgroups_groups">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.9.4</span>
</div><p>Note: this function is only available on POSIX platforms (i.e. not Windows,
Android)</p>
<p>Sets the supplementary group IDs. This is a privileged operation, meaning you
need to be root or have the <code>CAP_SETGID</code> capability.</p>
<p>The list can contain group IDs, group names or both.</p>
<h2>process.setuid(id)<span><a class="mark" href="#process_process_setuid_id" id="process_process_setuid_id">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.28</span>
</div><p>Note: this function is only available on POSIX platforms (i.e. not Windows,
Android)</p>
<p>Sets the user identity of the process. (See <a href="http://man7.org/linux/man-pages/man2/setuid.2.html">setuid(2)</a>.) This accepts either
a numerical ID or a username string. If a username is specified, this method
blocks while resolving it to a numerical ID.</p>
<pre><code class="lang-js">if (process.getuid && process.setuid) {
console.log(`Current uid: ${process.getuid()}`);
try {
process.setuid(501);
console.log(`New uid: ${process.getuid()}`);
}
catch (err) {
console.log(`Failed to set uid: ${err}`);
}
}
</code></pre>
<h2>process.stderr<span><a class="mark" href="#process_process_stderr" id="process_process_stderr">#</a></span></h2>
<p>A writable stream to stderr (on fd <code>2</code>).</p>
<p><code>process.stderr</code> and <code>process.stdout</code> are unlike other streams in Node.js in
that they cannot be closed (<code>end()</code> will throw), they never emit the <code>finish</code>
event and that writes can block when output is redirected to a file (although
disks are fast and operating systems normally employ write-back caching so it
should be a very rare occurrence indeed.)</p>
<p>Additionally, <code>process.stderr</code> and <code>process.stdout</code> are blocking when outputting
to TTYs (terminals) on OS X as a workaround for the OS's very small, 1kb
buffer size. This is to prevent interleaving between <code>stdout</code> and <code>stderr</code>.</p>
<h2>process.stdin<span><a class="mark" href="#process_process_stdin" id="process_process_stdin">#</a></span></h2>
<p>A <code>Readable Stream</code> for stdin (on fd <code>0</code>).</p>
<p>Example of opening standard input and listening for both events:</p>
<pre><code class="lang-js">process.stdin.setEncoding('utf8');
process.stdin.on('readable', () => {
var chunk = process.stdin.read();
if (chunk !== null) {
process.stdout.write(`data: ${chunk}`);
}
});
process.stdin.on('end', () => {
process.stdout.write('end');
});
</code></pre>
<p>As 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="stream.html#stream_compatibility_with_older_node_js_versions">Stream compatibility</a>.</p>
<p>In "old" Streams mode the stdin 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>
<p>If you are starting a new project you should prefer a more recent "new" Streams
mode over "old" one.</p>
<h2>process.stdout<span><a class="mark" href="#process_process_stdout" id="process_process_stdout">#</a></span></h2>
<p>A <code>Writable Stream</code> to <code>stdout</code> (on fd <code>1</code>).</p>
<p>For example, a <code>console.log</code> equivalent could look like this:</p>
<pre><code class="lang-js">console.log = (msg) => {
process.stdout.write(`${msg}\n`);
};
</code></pre>
<p><code>process.stderr</code> and <code>process.stdout</code> are unlike other streams in Node.js in
that they cannot be closed (<code>end()</code> will throw), they never emit the <code>'finish'</code>
event and that writes can block when output is redirected to a file (although
disks are fast and operating systems normally employ write-back caching so it
should be a very rare occurrence indeed.)</p>
<p>Additionally, <code>process.stderr</code> and <code>process.stdout</code> are blocking when outputting
to TTYs (terminals) on OS X as a workaround for the OS's very small, 1kb
buffer size. This is to prevent interleaving between <code>stdout</code> and <code>stderr</code>.</p>
<p>To check if Node.js is being run in a TTY context, read the <code>isTTY</code> property
on <code>process.stderr</code>, <code>process.stdout</code>, or <code>process.stdin</code>:</p>
<pre><code>$ node -p "Boolean(process.stdin.isTTY)"
true
$ echo "foo" | node -p "Boolean(process.stdin.isTTY)"
false
$ node -p "Boolean(process.stdout.isTTY)"
true
$ node -p "Boolean(process.stdout.isTTY)" | cat
false
</code></pre><p>See <a href="tty.html#tty_tty">the tty docs</a> for more information.</p>
<h2>process.title<span><a class="mark" href="#process_process_title" id="process_process_title">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.104</span>
</div><p>Getter/setter to set what is displayed in <code>ps</code>.</p>
<p>When used as a setter, the maximum length is platform-specific and probably
short.</p>
<p>On Linux and OS X, it's limited to the size of the binary name plus the
length of the command line arguments because it overwrites the argv memory.</p>
<p>v0.8 allowed for longer process title strings by also overwriting the environ
memory but that was potentially insecure/confusing in some (rather obscure)
cases.</p>
<h2>process.umask([mask])<span><a class="mark" href="#process_process_umask_mask" id="process_process_umask_mask">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.19</span>
</div><p>Sets or reads the process's file mode creation mask. Child processes inherit
the mask from the parent process. Returns the old mask if <code>mask</code> argument is
given, otherwise returns the current mask.</p>
<pre><code class="lang-js">const newmask = 0o022;
const oldmask = process.umask(newmask);
console.log(
`Changed umask from ${oldmask.toString(8)} to ${newmask.toString(8)}`
);
</code></pre>
<h2>process.uptime()<span><a class="mark" href="#process_process_uptime" id="process_process_uptime">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.0</span>
</div><p>Number of seconds Node.js has been running.</p>
<h2>process.version<span><a class="mark" href="#process_process_version" id="process_process_version">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.3</span>
</div><p>A compiled-in property that exposes <code>NODE_VERSION</code>.</p>
<pre><code class="lang-js">console.log(`Version: ${process.version}`);
</code></pre>
<h2>process.versions<span><a class="mark" href="#process_process_versions" id="process_process_versions">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.2.0</span>
</div><p>A property exposing version strings of Node.js and its dependencies.</p>
<pre><code class="lang-js">console.log(process.versions);
</code></pre>
<p>Will print something like:</p>
<pre><code class="lang-js">{ http_parser: '2.3.0',
node: '1.1.1',
v8: '4.1.0.14',
uv: '1.3.0',
zlib: '1.2.8',
ares: '1.10.0-DEV',
modules: '43',
icu: '55.1',
openssl: '1.0.1k' }
</code></pre>
<!-- [end-include:process.md] -->
<!-- [start-include:punycode.md] -->
<h1>Punycode<span><a class="mark" href="#punycode_punycode" id="punycode_punycode">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p><a href="https://mths.be/punycode">Punycode.js</a> is bundled with Node.js v0.5.1+. Use <code>require('punycode')</code> to
access it. (To use it with other Node.js versions, use npm to install the
<code>punycode</code> module first.)</p>
<h2>punycode.decode(string)<span><a class="mark" href="#punycode_punycode_decode_string" id="punycode_punycode_decode_string">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.1</span>
</div><p>Converts a Punycode string of ASCII-only symbols to a string of Unicode symbols.</p>
<pre><code class="lang-js">// decode domain name parts
punycode.decode('maana-pta'); // 'mañana'
punycode.decode('--dqo34k'); // '☃-⌘'
</code></pre>
<h2>punycode.encode(string)<span><a class="mark" href="#punycode_punycode_encode_string" id="punycode_punycode_encode_string">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.1</span>
</div><p>Converts a string of Unicode symbols to a Punycode string of ASCII-only symbols.</p>
<pre><code class="lang-js">// encode domain name parts
punycode.encode('mañana'); // 'maana-pta'
punycode.encode('☃-⌘'); // '--dqo34k'
</code></pre>
<h2>punycode.toASCII(domain)<span><a class="mark" href="#punycode_punycode_toascii_domain" id="punycode_punycode_toascii_domain">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.6.1</span>
</div><p>Converts a Unicode string representing a domain name to Punycode. Only the
non-ASCII parts of the domain name will be converted, i.e. it doesn't matter if
you call it with a domain that's already in ASCII.</p>
<pre><code class="lang-js">// encode domain names
punycode.toASCII('mañana.com'); // 'xn--maana-pta.com'
punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com'
</code></pre>
<h2>punycode.toUnicode(domain)<span><a class="mark" href="#punycode_punycode_tounicode_domain" id="punycode_punycode_tounicode_domain">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.6.1</span>
</div><p>Converts a Punycode string representing a domain name to Unicode. Only the
Punycoded parts of the domain name will be converted, i.e. it doesn't matter if
you call it on a string that has already been converted to Unicode.</p>
<pre><code class="lang-js">// decode domain names
punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'
punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com'
</code></pre>
<h2>punycode.ucs2<span><a class="mark" href="#punycode_punycode_ucs2" id="punycode_punycode_ucs2">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div><h3>punycode.ucs2.decode(string)<span><a class="mark" href="#punycode_punycode_ucs2_decode_string" id="punycode_punycode_ucs2_decode_string">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div><p>Creates an array containing the numeric code point values of each Unicode
symbol in the string. While <a href="https://mathiasbynens.be/notes/javascript-encoding">JavaScript uses UCS-2 internally</a>, this function
will convert a pair of surrogate halves (each of which UCS-2 exposes as
separate characters) into a single code point, matching UTF-16.</p>
<pre><code class="lang-js">punycode.ucs2.decode('abc'); // [0x61, 0x62, 0x63]
// surrogate pair for U+1D306 tetragram for centre:
punycode.ucs2.decode('\uD834\uDF06'); // [0x1D306]
</code></pre>
<h3>punycode.ucs2.encode(codePoints)<span><a class="mark" href="#punycode_punycode_ucs2_encode_codepoints" id="punycode_punycode_ucs2_encode_codepoints">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.0</span>
</div><p>Creates a string based on an array of numeric code point values.</p>
<pre><code class="lang-js">punycode.ucs2.encode([0x61, 0x62, 0x63]); // 'abc'
punycode.ucs2.encode([0x1D306]); // '\uD834\uDF06'
</code></pre>
<h2>punycode.version<span><a class="mark" href="#punycode_punycode_version" id="punycode_punycode_version">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.6.1</span>
</div><p>A string representing the current Punycode.js version number.</p>
<!-- [end-include:punycode.md] -->
<!-- [start-include:querystring.md] -->
<h1>Query String<span><a class="mark" href="#querystring_query_string" id="querystring_query_string">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><!--name=querystring-->
<p>This module provides utilities for dealing with query strings.
It provides the following methods:</p>
<h2>querystring.escape<span><a class="mark" href="#querystring_querystring_escape" id="querystring_querystring_escape">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.25</span>
</div><p>The escape function used by <code>querystring.stringify</code>,
provided so that it could be overridden if necessary.</p>
<h2>querystring.parse(str[, sep][, eq][, options])<span><a class="mark" href="#querystring_querystring_parse_str_sep_eq_options" id="querystring_querystring_parse_str_sep_eq_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.25</span>
</div><p>Deserialize a query string to an object.
Optionally override the default separator (<code>'&'</code>) and assignment (<code>'='</code>)
characters.</p>
<p>Options object may contain <code>maxKeys</code> property (equal to 1000 by default), it'll
be used to limit processed keys. Set it to 0 to remove key count limitation.</p>
<p>Options object may contain <code>decodeURIComponent</code> property (<code>querystring.unescape</code> by default),
it can be used to decode a <code>non-utf8</code> encoding string if necessary.</p>
<p>Example:</p>
<pre><code class="lang-js">querystring.parse('foo=bar&baz=qux&baz=quux&corge')
// returns { foo: 'bar', baz: ['qux', 'quux'], corge: '' }
// Suppose gbkDecodeURIComponent function already exists,
// it can decode `gbk` encoding string
querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null,
{ decodeURIComponent: gbkDecodeURIComponent })
// returns { w: 'ä¸æ–‡', foo: 'bar' }
</code></pre>
<h2>querystring.stringify(obj[, sep][, eq][, options])<span><a class="mark" href="#querystring_querystring_stringify_obj_sep_eq_options" id="querystring_querystring_stringify_obj_sep_eq_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.25</span>
</div><p>Serialize an object to a query string.
Optionally override the default separator (<code>'&'</code>) and assignment (<code>'='</code>)
characters.</p>
<p>Options object may contain <code>encodeURIComponent</code> property (<code>querystring.escape</code> by default),
it can be used to encode string with <code>non-utf8</code> encoding if necessary.</p>
<p>Example:</p>
<pre><code class="lang-js">querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' })
// returns 'foo=bar&baz=qux&baz=quux&corge='
querystring.stringify({foo: 'bar', baz: 'qux'}, ';', ':')
// returns 'foo:bar;baz:qux'
// Suppose gbkEncodeURIComponent function already exists,
// it can encode string with `gbk` encoding
querystring.stringify({ w: 'ä¸æ–‡', foo: 'bar' }, null, null,
{ encodeURIComponent: gbkEncodeURIComponent })
// returns 'w=%D6%D0%CE%C4&foo=bar'
</code></pre>
<h2>querystring.unescape<span><a class="mark" href="#querystring_querystring_unescape" id="querystring_querystring_unescape">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.25</span>
</div><p>The unescape function used by <code>querystring.parse</code>,
provided so that it could be overridden if necessary.</p>
<p>It will try to use <code>decodeURIComponent</code> in the first place,
but if that fails it falls back to a safer equivalent that
doesn't throw on malformed URLs.</p>
<!-- [end-include:querystring.md] -->
<!-- [start-include:readline.md] -->
<h1>Readline<span><a class="mark" href="#readline_readline" id="readline_readline">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>To use this module, do <code>require('readline')</code>. Readline allows reading of a
stream (such as <a href="process.html#process_process_stdin"><code>process.stdin</code></a>) on a line-by-line basis.</p>
<p>Note that once you've invoked this module, your Node.js program will not
terminate until you've closed the interface. Here's how to allow your
program to gracefully exit:</p>
<pre><code class="lang-js">const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question('What do you think of Node.js? ', (answer) => {
// TODO: Log the answer in a database
console.log('Thank you for your valuable feedback:', answer);
rl.close();
});
</code></pre>
<h2>Class: Interface<span><a class="mark" href="#readline_class_interface" id="readline_class_interface">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.104</span>
</div><p>The class that represents a readline interface with an input and output
stream.</p>
<h3>rl.close()<span><a class="mark" href="#readline_rl_close" id="readline_rl_close">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.98</span>
</div><p>Closes the <code>Interface</code> instance, relinquishing control on the <code>input</code> and
<code>output</code> streams. The <code>'close'</code> event will also be emitted.</p>
<h3>rl.pause()<span><a class="mark" href="#readline_rl_pause" id="readline_rl_pause">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.4</span>
</div><p>Pauses the readline <code>input</code> stream, allowing it to be resumed later if needed.</p>
<p>Note that this doesn't immediately pause the stream of events. Several events may
be emitted after calling <code>pause</code>, including <code>line</code>.</p>
<h3>rl.prompt([preserveCursor])<span><a class="mark" href="#readline_rl_prompt_preservecursor" id="readline_rl_prompt_preservecursor">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.98</span>
</div><p>Readies readline for input from the user, putting the current <code>setPrompt</code>
options on a new line, giving the user a new spot to write. Set <code>preserveCursor</code>
to <code>true</code> to prevent the cursor placement being reset to <code>0</code>.</p>
<p>This will also resume the <code>input</code> stream used with <code>createInterface</code> if it has
been paused.</p>
<p>If <code>output</code> is set to <code>null</code> or <code>undefined</code> when calling <code>createInterface</code>, the
prompt is not written.</p>
<h3>rl.question(query, callback)<span><a class="mark" href="#readline_rl_question_query_callback" id="readline_rl_question_query_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.3</span>
</div><p>Prepends the prompt with <code>query</code> and invokes <code>callback</code> with the user's
response. Displays the query to the user, and then invokes <code>callback</code>
with the user's response after it has been typed.</p>
<p>This will also resume the <code>input</code> stream used with <code>createInterface</code> if
it has been paused.</p>
<p>If <code>output</code> is set to <code>null</code> or <code>undefined</code> when calling <code>createInterface</code>,
nothing is displayed.</p>
<p>Example usage:</p>
<pre><code class="lang-js">rl.question('What is your favorite food?', (answer) => {
console.log(`Oh, so your favorite food is ${answer}`);
});
</code></pre>
<h3>rl.resume()<span><a class="mark" href="#readline_rl_resume" id="readline_rl_resume">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.4</span>
</div><p>Resumes the readline <code>input</code> stream.</p>
<h3>rl.setPrompt(prompt)<span><a class="mark" href="#readline_rl_setprompt_prompt" id="readline_rl_setprompt_prompt">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.98</span>
</div><p>Sets the prompt, for example when you run <code>node</code> on the command line, you see
<code>></code>, which is Node.js's prompt.</p>
<h3>rl.write(data[, key])<span><a class="mark" href="#readline_rl_write_data_key" id="readline_rl_write_data_key">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.98</span>
</div><p>Writes <code>data</code> to <code>output</code> stream, unless <code>output</code> is set to <code>null</code> or
<code>undefined</code> when calling <code>createInterface</code>. <code>key</code> is an object literal to
represent a key sequence; available if the terminal is a TTY.</p>
<p>This will also resume the <code>input</code> stream if it has been paused.</p>
<p>Example:</p>
<pre><code class="lang-js">rl.write('Delete me!');
// Simulate ctrl+u to delete the line written previously
rl.write(null, {ctrl: true, name: 'u'});
</code></pre>
<h2>Events<span><a class="mark" href="#readline_events" id="readline_events">#</a></span></h2>
<h3>Event: 'close'<span><a class="mark" href="#readline_event_close" id="readline_event_close">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.98</span>
</div><p><code>function () {}</code></p>
<p>Emitted when <code>close()</code> is called.</p>
<p>Also emitted when the <code>input</code> stream receives its <code>'end'</code> event. The <code>Interface</code>
instance should be considered "finished" once this is emitted. For example, when
the <code>input</code> stream receives <code>^D</code>, respectively known as <code>EOT</code>.</p>
<p>This event is also called if there is no <code>SIGINT</code> event listener present when
the <code>input</code> stream receives a <code>^C</code>, respectively known as <code>SIGINT</code>.</p>
<h3>Event: 'line'<span><a class="mark" href="#readline_event_line" id="readline_event_line">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.98</span>
</div><p><code>function (line) {}</code></p>
<p>Emitted whenever the <code>input</code> stream receives an end of line (<code>\n</code>, <code>\r</code>, or
<code>\r\n</code>), usually received when the user hits enter, or return. This is a good
hook to listen for user input.</p>
<p>Example of listening for <code>'line'</code>:</p>
<pre><code class="lang-js">rl.on('line', (cmd) => {
console.log(`You just typed: ${cmd}`);
});
</code></pre>
<h3>Event: 'pause'<span><a class="mark" href="#readline_event_pause" id="readline_event_pause">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.5</span>
</div><p><code>function () {}</code></p>
<p>Emitted whenever the <code>input</code> stream is paused.</p>
<p>Also emitted whenever the <code>input</code> stream is not paused and receives the
<code>SIGCONT</code> event. (See events <code>SIGTSTP</code> and <code>SIGCONT</code>)</p>
<p>Example of listening for <code>'pause'</code>:</p>
<pre><code class="lang-js">rl.on('pause', () => {
console.log('Readline paused.');
});
</code></pre>
<h3>Event: 'resume'<span><a class="mark" href="#readline_event_resume" id="readline_event_resume">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.5</span>
</div><p><code>function () {}</code></p>
<p>Emitted whenever the <code>input</code> stream is resumed.</p>
<p>Example of listening for <code>'resume'</code>:</p>
<pre><code class="lang-js">rl.on('resume', () => {
console.log('Readline resumed.');
});
</code></pre>
<h3>Event: 'SIGCONT'<span><a class="mark" href="#readline_event_sigcont" id="readline_event_sigcont">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.5</span>
</div><p><code>function () {}</code></p>
<p><strong>This does not work on Windows.</strong></p>
<p>Emitted whenever the <code>input</code> stream is sent to the background with <code>^Z</code>,
respectively known as <code>SIGTSTP</code>, and then continued with <a href="http://man7.org/linux/man-pages/man1/fg.1.html">fg(1)</a>. This event
only emits if the stream was not paused before sending the program to the
background.</p>
<p>Example of listening for <code>SIGCONT</code>:</p>
<pre><code class="lang-js">rl.on('SIGCONT', () => {
// `prompt` will automatically resume the stream
rl.prompt();
});
</code></pre>
<h3>Event: 'SIGINT'<span><a class="mark" href="#readline_event_sigint" id="readline_event_sigint">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div><p><code>function () {}</code></p>
<p>Emitted whenever the <code>input</code> stream receives a <code>^C</code>, respectively known as
<code>SIGINT</code>. If there is no <code>SIGINT</code> event listener present when the <code>input</code>
stream receives a <code>SIGINT</code>, <code>pause</code> will be triggered.</p>
<p>Example of listening for <code>SIGINT</code>:</p>
<pre><code class="lang-js">rl.on('SIGINT', () => {
rl.question('Are you sure you want to exit?', (answer) => {
if (answer.match(/^y(es)?$/i)) rl.pause();
});
});
</code></pre>
<h3>Event: 'SIGTSTP'<span><a class="mark" href="#readline_event_sigtstp" id="readline_event_sigtstp">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.5</span>
</div><p><code>function () {}</code></p>
<p><strong>This does not work on Windows.</strong></p>
<p>Emitted whenever the <code>input</code> stream receives a <code>^Z</code>, respectively known as
<code>SIGTSTP</code>. If there is no <code>SIGTSTP</code> event listener present when the <code>input</code>
stream receives a <code>SIGTSTP</code>, the program will be sent to the background.</p>
<p>When the program is resumed with <code>fg</code>, the <code>'pause'</code> and <code>SIGCONT</code> events will be
emitted. You can use either to resume the stream.</p>
<p>The <code>'pause'</code> and <code>SIGCONT</code> events will not be triggered if the stream was paused
before the program was sent to the background.</p>
<p>Example of listening for <code>SIGTSTP</code>:</p>
<pre><code class="lang-js">rl.on('SIGTSTP', () => {
// This will override SIGTSTP and prevent the program from going to the
// background.
console.log('Caught SIGTSTP.');
});
</code></pre>
<h2>Example: Tiny CLI<span><a class="mark" href="#readline_example_tiny_cli" id="readline_example_tiny_cli">#</a></span></h2>
<p>Here's an example of how to use all these together to craft a tiny command
line interface:</p>
<pre><code class="lang-js">const readline = require('readline');
const rl = readline.createInterface(process.stdin, process.stdout);
rl.setPrompt('OHAI> ');
rl.prompt();
rl.on('line', (line) => {
switch(line.trim()) {
case 'hello':
console.log('world!');
break;
default:
console.log('Say what? I might have heard `' + line.trim() + '`');
break;
}
rl.prompt();
}).on('close', () => {
console.log('Have a great day!');
process.exit(0);
});
</code></pre>
<h2>Example: Read File Stream Line-by-Line<span><a class="mark" href="#readline_example_read_file_stream_line_by_line" id="readline_example_read_file_stream_line_by_line">#</a></span></h2>
<p>A common case for <code>readline</code>'s <code>input</code> option is to pass a filesystem readable
stream to it. This is how one could craft line-by-line parsing of a file:</p>
<pre><code class="lang-js">const readline = require('readline');
const fs = require('fs');
const rl = readline.createInterface({
input: fs.createReadStream('sample.txt')
});
rl.on('line', (line) => {
console.log('Line from file:', line);
});
</code></pre>
<p><em>Note</em>: The <code>rl.write()</code> method will write the data to the <code>readline</code>
Interface's <code>input</code> <em>as if it were provided by the user</em>.</p>
<h2>readline.clearLine(stream, dir)<span><a class="mark" href="#readline_readline_clearline_stream_dir" id="readline_readline_clearline_stream_dir">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div><p>Clears current line of given TTY stream in a specified direction.
<code>dir</code> should have one of following values:</p>
<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>
<h2>readline.clearScreenDown(stream)<span><a class="mark" href="#readline_readline_clearscreendown_stream" id="readline_readline_clearscreendown_stream">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div><p>Clears the screen from the current position of the cursor down.</p>
<h2>readline.createInterface(options)<span><a class="mark" href="#readline_readline_createinterface_options" id="readline_readline_createinterface_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.98</span>
</div><p>Creates a readline <code>Interface</code> instance. Accepts an <code>options</code> Object that takes
the following values:</p>
<ul>
<li><p><code>input</code> - the readable stream to listen to (Required).</p>
</li>
<li><p><code>output</code> - the writable stream to write readline data to (Optional).</p>
</li>
<li><p><code>completer</code> - an optional function that is used for Tab autocompletion. See
below for an example of using this.</p>
</li>
<li><p><code>terminal</code> - pass <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.
Defaults to checking <code>isTTY</code> on the <code>output</code> stream upon instantiation.</p>
</li>
<li><p><code>historySize</code> - maximum number of history lines retained. Defaults to <code>30</code>.</p>
</li>
</ul>
<p>The <code>completer</code> function is given the current line entered by the user, and
is supposed to return an Array with 2 entries:</p>
<ol>
<li><p>An Array with matching entries for the completion.</p>
</li>
<li><p>The substring that was used for the matching.</p>
</li>
</ol>
<p>Which ends up looking something like:
<code>[[substr1, substr2, ...], originalsubstring]</code>.</p>
<p>Example:</p>
<pre><code class="lang-js">function completer(line) {
var completions = '.help .error .exit .quit .q'.split(' ')
var hits = completions.filter((c) => { return c.indexOf(line) == 0 })
// show all completions if none found
return [hits.length ? hits : completions, line]
}
</code></pre>
<p>Also <code>completer</code> can be run in async mode if it accepts two arguments:</p>
<pre><code class="lang-js">function completer(linePartial, callback) {
callback(null, [['123'], linePartial]);
}
</code></pre>
<p><code>createInterface</code> is commonly used with <a href="process.html#process_process_stdin"><code>process.stdin</code></a> and
<a href="process.html#process_process_stdout"><code>process.stdout</code></a> in order to accept user input:</p>
<pre><code class="lang-js">const readline = require('readline');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
</code></pre>
<p>Once you have a readline instance, you most commonly listen for the
<code>'line'</code> event.</p>
<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 fires
a <code>'resize'</code> event on the <code>output</code> if/when the columns ever change
(<a href="process.html#process_process_stdout"><code>process.stdout</code></a> does this automatically when it is a TTY).</p>
<h2>readline.cursorTo(stream, x, y)<span><a class="mark" href="#readline_readline_cursorto_stream_x_y" id="readline_readline_cursorto_stream_x_y">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div><p>Move cursor to the specified position in a given TTY stream.</p>
<h2>readline.emitKeypressEvents(stream[, interface])<span><a class="mark" href="#readline_readline_emitkeypressevents_stream_interface" id="readline_readline_emitkeypressevents_stream_interface">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div><p>Causes <code>stream</code> to begin emitting <code>'keypress'</code> events corresponding to its
input.
Optionally, <code>interface</code> specifies a <code>readline.Interface</code> instance for which
autocompletion is disabled when copy-pasted input is detected.</p>
<h2>readline.moveCursor(stream, dx, dy)<span><a class="mark" href="#readline_readline_movecursor_stream_dx_dy" id="readline_readline_movecursor_stream_dx_dy">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div><p>Move cursor relative to it's current position in a given TTY stream.</p>
<!-- [end-include:readline.md] -->
<!-- [start-include:repl.md] -->
<h1>REPL<span><a class="mark" href="#repl_repl" id="repl_repl">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>A Read-Eval-Print-Loop (REPL) is available both as a standalone program and
easily includable in other programs. The REPL provides a way to interactively
run JavaScript and see the results. It can be used for debugging, testing, or
just trying things out.</p>
<p>By executing <code>node</code> without any arguments from the command-line you will be
dropped into the REPL. It has simplistic emacs line-editing.</p>
<pre><code>$ node
Type '.help' for options.
> a = [1, 2, 3];
[ 1, 2, 3 ]
> a.forEach((v) => {
... console.log(v);
... });
1
2
3
</code></pre><p>For advanced line-editors, start Node.js with the environmental variable
<code>NODE_NO_READLINE=1</code>. This will start the main and debugger REPL in canonical
terminal settings which will allow you to use with <code>rlwrap</code>.</p>
<p>For example, you could add this to your bashrc file:</p>
<pre><code>alias node="env NODE_NO_READLINE=1 rlwrap node"
</code></pre><h2>Environment Variable Options<span><a class="mark" href="#repl_environment_variable_options" id="repl_environment_variable_options">#</a></span></h2>
<p>The built-in repl (invoked by running <code>node</code> or <code>node -i</code>) may be controlled
via 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> will disable persistent
REPL history. Whitespace will be trimmed from the value.</li>
<li><code>NODE_REPL_HISTORY_SIZE</code> - Defaults to <code>1000</code>. Controls how many lines of
history will be persisted if history is available. Must be a positive number.</li>
<li><code>NODE_REPL_MODE</code> - May be any of <code>sloppy</code>, <code>strict</code>, or <code>magic</code>. Defaults
to <code>magic</code>, which will automatically run "strict mode only" statements in
strict mode.</li>
</ul>
<h2>Persistent History<span><a class="mark" href="#repl_persistent_history" id="repl_persistent_history">#</a></span></h2>
<p>By default, the REPL will persist history between <code>node</code> REPL sessions by saving
to a <code>.node_repl_history</code> file in the user's home directory. This can be
disabled by setting the environment variable <code>NODE_REPL_HISTORY=""</code>.</p>
<h3>NODE_REPL_HISTORY_FILE<span><a class="mark" href="#repl_node_repl_history_file" id="repl_node_repl_history_file">#</a></span></h3>
<pre class="api_stability api_stability_0">Stability: 0 - Deprecated: Use <code>NODE_REPL_HISTORY</code> instead.</pre><p>Previously in Node.js/io.js v2.x, REPL history was controlled by using a
<code>NODE_REPL_HISTORY_FILE</code> environment variable, and the history was saved in JSON
format. This variable has now been deprecated, and your REPL history will
automatically be converted to using plain text. The new file will be saved to
either your home directory, or a directory defined by the <code>NODE_REPL_HISTORY</code>
variable, as documented <a href="#repl_environment_variable_options">here</a>.</p>
<h2>REPL Features<span><a class="mark" href="#repl_repl_features" id="repl_repl_features">#</a></span></h2>
<!-- type=misc -->
<p>Inside the REPL, Control+D will exit. Multi-line expressions can be input.
Tab completion is supported for both global and local variables.</p>
<p>Core modules will be loaded on-demand into the environment. For example,
accessing <code>fs</code> will <code>require()</code> the <code>fs</code> module as <code>global.fs</code>.</p>
<p>The special variable <code>_</code> (underscore) contains the result of the last expression.</p>
<pre><code>> [ 'a', 'b', 'c' ]
[ 'a', 'b', 'c' ]
> _.length
3
> _ += 1
4
</code></pre><p>The REPL provides access to any variables in the global scope. You can expose
a variable to the REPL explicitly by assigning it to the <code>context</code> object
associated with each <code>REPLServer</code>. For example:</p>
<pre><code class="lang-js">// repl_test.js
const repl = require('repl');
var msg = 'message';
repl.start('> ').context.m = msg;
</code></pre>
<p>Things in the <code>context</code> object appear as local within the REPL:</p>
<pre><code>$ node repl_test.js
> m
'message'
</code></pre><p>There are a few special REPL commands:</p>
<ul>
<li><code>.break</code> - While inputting a multi-line expression, sometimes you get lost
or just don't care about completing it. <code>.break</code> will start over.</li>
<li><code>.clear</code> - Resets the <code>context</code> object to an empty object and clears any
multi-line expression.</li>
<li><code>.exit</code> - Close the I/O stream, which will cause 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
.save ./file/to/save.js</li>
<li><code>.load</code> - Load a file into the current REPL session.
.load ./file/to/load.js</li>
</ul>
<p>The following key combinations in the REPL have these special effects:</p>
<ul>
<li><code><ctrl>C</code> - Similar to the <code>.break</code> keyword. Terminates the current
command. Press twice on a blank line to forcibly exit.</li>
<li><code><ctrl>D</code> - Similar to the <code>.exit</code> keyword.</li>
<li><code><tab></code> - Show both global and local(scope) variables</li>
</ul>
<h3>Customizing Object displays in the REPL<span><a class="mark" href="#repl_customizing_object_displays_in_the_repl" id="repl_customizing_object_displays_in_the_repl">#</a></span></h3>
<p>The REPL module internally uses
<a href="util.html#util_util_inspect_object_options"><code>util.inspect()</code></a>, when printing values. However, <code>util.inspect</code> delegates the
call to the object's <code>inspect()</code> function, if it has one. You can read more
about this delegation <a href="https://github.com/thlorenz/v8-flags/blob/master/flags-0.11.md">here</a>.</p>
<p>For example, if you have defined an <code>inspect()</code> function on an object, like this:</p>
<pre><code>> var obj = {foo: 'this will not show up in the inspect() output'};
undefined
> obj.inspect = () => {
... return {bar: 'baz'};
... };
[Function]
</code></pre><p>and try to print <code>obj</code> in REPL, it will invoke the custom <code>inspect()</code> function:</p>
<pre><code>> obj
{bar: 'baz'}
</code></pre><h2>Class: REPLServer<span><a class="mark" href="#repl_class_replserver" id="repl_class_replserver">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.91</span>
</div><p>This inherits from <a href="readline.html#readline_class_interface">Readline Interface</a> with the following events:</p>
<h3>Event: 'exit'<span><a class="mark" href="#repl_event_exit" id="repl_event_exit">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div><p><code>function () {}</code></p>
<p>Emitted when the user exits the REPL in any of the defined ways. Namely, typing
<code>.exit</code> at the repl, pressing Ctrl+C twice to signal <code>SIGINT</code>, or pressing Ctrl+D
to signal <code>'end'</code> on the <code>input</code> stream.</p>
<p>Example of listening for <code>exit</code>:</p>
<pre><code class="lang-js">replServer.on('exit', () => {
console.log('Got "exit" event from repl!');
process.exit();
});
</code></pre>
<h3>Event: 'reset'<span><a class="mark" href="#repl_event_reset" id="repl_event_reset">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.0</span>
</div><p><code>function (context) {}</code></p>
<p>Emitted when the REPL's context is reset. This happens when you type <code>.clear</code>.
If you start the repl with <code>{ useGlobal: true }</code> then this event will never
be emitted.</p>
<p>Example of listening for <code>reset</code>:</p>
<pre><code class="lang-js">// Extend the initial repl context.
var replServer = repl.start({ options ... });
someExtension.extend(r.context);
// When a new context is created extend it as well.
replServer.on('reset', (context) => {
console.log('repl has a new context');
someExtension.extend(context);
});
</code></pre>
<h3>replServer.defineCommand(keyword, cmd)<span><a class="mark" href="#repl_replserver_definecommand_keyword_cmd" id="repl_replserver_definecommand_keyword_cmd">#</a></span></h3>
<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></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></li>
</ul>
<p>Makes a command available in the REPL. The command is invoked by typing a <code>.</code>
followed by the keyword. The <code>cmd</code> is an object with the following values:</p>
<ul>
<li><code>help</code> - help text to be displayed when <code>.help</code> is entered (Optional).</li>
<li><code>action</code> - a function to execute, potentially taking in a string argument,
when the command is invoked, bound to the REPLServer instance (Required).</li>
</ul>
<p>If a function is provided instead of an object for <code>cmd</code>, it is treated as the
<code>action</code>.</p>
<p>Example of defining a command:</p>
<pre><code class="lang-js">// repl_test.js
const repl = require('repl');
var replServer = repl.start();
replServer.defineCommand('sayhello', {
help: 'Say hello',
action: function(name) {
this.write(`Hello, ${name}!\n`);
this.displayPrompt();
}
});
</code></pre>
<p>Example of invoking that command from the REPL:</p>
<pre><code>> .sayhello Node.js User
Hello, Node.js User!
</code></pre><h3>replServer.displayPrompt([preserveCursor])<span><a class="mark" href="#repl_replserver_displayprompt_preservecursor" id="repl_replserver_displayprompt_preservecursor">#</a></span></h3>
<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>Like <a href="readline.html#readline_rl_prompt_preservecursor"><code>readline.prompt</code></a> except also adding indents with ellipses when inside
blocks. The <code>preserveCursor</code> argument is passed to <a href="readline.html#readline_rl_prompt_preservecursor"><code>readline.prompt</code></a>. This is
used primarily with <code>defineCommand</code>. It's also used internally to render each
prompt line.</p>
<h2>repl.start(options)<span><a class="mark" href="#repl_repl_start_options" id="repl_repl_start_options">#</a></span></h2>
<p>Returns and starts a <code>REPLServer</code> instance, that inherits from
<a href="readline.html#readline_class_interface">Readline Interface</a>. Accepts an "options" Object that takes
the following values:</p>
<ul>
<li><p><code>prompt</code> - the prompt and <code>stream</code> for all I/O. Defaults to <code>></code>.</p>
</li>
<li><p><code>input</code> - the readable stream to listen to. Defaults to <code>process.stdin</code>.</p>
</li>
<li><p><code>output</code> - the writable stream to write readline data to. Defaults to
<code>process.stdout</code>.</p>
</li>
<li><p><code>terminal</code> - pass <code>true</code> if the <code>stream</code> should be treated like a TTY, and
have ANSI/VT100 escape codes written to it. Defaults to checking <code>isTTY</code>
on the <code>output</code> stream upon instantiation.</p>
</li>
<li><p><code>eval</code> - function that will be used to eval each given line. Defaults to
an async wrapper for <code>eval()</code>. See below for an example of a custom <code>eval</code>.</p>
</li>
<li><p><code>useColors</code> - a boolean which specifies whether or not the <code>writer</code> function
should output colors. If a different <code>writer</code> function is set then this does
nothing. Defaults to the repl's <code>terminal</code> value.</p>
</li>
<li><p><code>useGlobal</code> - if set to <code>true</code>, then the repl will use the <code>global</code> object,
instead of running scripts in a separate context. Defaults to <code>false</code>.</p>
</li>
<li><p><code>ignoreUndefined</code> - if set to <code>true</code>, then the repl will not output the
return value of command if it's <code>undefined</code>. Defaults to <code>false</code>.</p>
</li>
<li><p><code>writer</code> - the function to invoke for each command that gets evaluated which
returns the formatting (including coloring) to display. Defaults to
<code>util.inspect</code>.</p>
</li>
<li><p><code>replMode</code> - controls whether the repl runs all commands in strict mode,
default mode, or a hybrid mode ("magic" mode.) Acceptable values are:</p>
<ul>
<li><code>repl.REPL_MODE_SLOPPY</code> - run commands in sloppy mode.</li>
<li><code>repl.REPL_MODE_STRICT</code> - run commands in strict mode. This is equivalent to
prefacing every repl statement with <code>'use strict'</code>.</li>
<li><code>repl.REPL_MODE_MAGIC</code> - attempt to run commands in default mode. If they
fail to parse, re-try in strict mode.</li>
</ul>
</li>
</ul>
<p>You can use your own <code>eval</code> function if it has following signature:</p>
<pre><code>function eval(cmd, context, filename, callback) {
callback(null, result);
}
</code></pre><p>On tab completion, <code>eval</code> will be called with <code>.scope</code> as an input string. It
is expected to return an array of scope names to be used for the auto-completion.</p>
<p>Multiple REPLs may be started against the same running instance of Node.js. Each
will share the same global object but will have unique I/O.</p>
<p>Here is an example that starts a REPL on stdin, a Unix socket, and a TCP socket:</p>
<pre><code class="lang-js">const net = require('net');
const repl = require('repl');
var connections = 0;
repl.start({
prompt: 'Node.js via stdin> ',
input: process.stdin,
output: process.stdout
});
net.createServer((socket) => {
connections += 1;
repl.start({
prompt: 'Node.js via Unix socket> ',
input: socket,
output: socket
}).on('exit', () => {
socket.end();
})
}).listen('/tmp/node-repl-sock');
net.createServer((socket) => {
connections += 1;
repl.start({
prompt: 'Node.js via TCP socket> ',
input: socket,
output: socket
}).on('exit', () => {
socket.end();
});
}).listen(5001);
</code></pre>
<p>Running this program 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> is useful
for connecting to TCP sockets, and <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, you can
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/2209310">https://gist.github.com/2209310</a></p>
<p>For an example of running a REPL instance over <a href="http://man7.org/linux/man-pages/man1/curl.1.html">curl(1)</a>,
see: <a href="https://gist.github.com/2053342">https://gist.github.com/2053342</a></p>
<!-- [end-include:repl.md] -->
<!-- [start-include:stream.md] -->
<h1>Stream<span><a class="mark" href="#stream_stream" id="stream_stream">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>A stream is an abstract interface implemented by various objects in
Node.js. For example a <a href="http.html#http_class_http_incomingmessage">request to an HTTP server</a> is a
stream, as is <a href="process.html#process_process_stdout"><code>process.stdout</code></a>. Streams are readable, writable, or both. All
streams are instances of <a href="events.html#events_class_eventemitter"><code>EventEmitter</code></a>.</p>
<p>You can load the Stream base classes by doing <code>require('stream')</code>.
There are base classes provided for <a href="#stream_class_stream_readable">Readable</a> streams, <a href="#stream_class_stream_writable">Writable</a>
streams, <a href="#stream_class_stream_duplex">Duplex</a> streams, and <a href="#stream_class_stream_transform">Transform</a> streams.</p>
<p>This document is split up into 3 sections:</p>
<ol>
<li>The first section explains the parts of the API that you need to be
aware of to use streams in your programs.</li>
<li>The second section explains the parts of the API that you need to
use if you implement your own custom streams yourself. The API is designed to
make this easy for you to do.</li>
<li>The third section goes into more depth about how streams work,
including some of the internal mechanisms and functions that you
should probably not modify unless you definitely know what you are
doing.</li>
</ol>
<h2>API for Stream Consumers<span><a class="mark" href="#stream_api_for_stream_consumers" id="stream_api_for_stream_consumers">#</a></span></h2>
<!--type=misc-->
<p>Streams can be either <a href="#stream_class_stream_readable">Readable</a>, <a href="#stream_class_stream_writable">Writable</a>, or both (<a href="#stream_class_stream_duplex">Duplex</a>).</p>
<p>All streams are EventEmitters, but they also have other custom methods
and properties depending on whether they are Readable, Writable, or
Duplex.</p>
<p>If a stream is both Readable and Writable, then it implements all of
the methods and events. So, a <a href="#stream_class_stream_duplex">Duplex</a> or <a href="#stream_class_stream_transform">Transform</a> stream is
fully described by this API, though their implementation may be
somewhat different.</p>
<p>It is not necessary to implement Stream interfaces in order to consume
streams in your programs. If you <strong>are</strong> implementing streaming
interfaces in your own program, please also refer to
<a href="#stream_api_for_stream_implementors">API for Stream Implementors</a>.</p>
<p>Almost all Node.js programs, no matter how simple, use Streams in some
way. Here is an example of using Streams in an Node.js program:</p>
<pre><code class="lang-js">const http = require('http');
var server = http.createServer( (req, res) => {
// req is an http.IncomingMessage, which is a Readable Stream
// res is an http.ServerResponse, which is a Writable Stream
var body = '';
// we want to get the data as utf8 strings
// If you don't set an encoding, then you'll get Buffer objects
req.setEncoding('utf8');
// Readable streams emit 'data' events once a listener is added
req.on('data', (chunk) => {
body += chunk;
});
// the end event tells you that you have entire body
req.on('end', () => {
try {
const data = JSON.parse(body);
// write back something interesting to the user:
res.write(typeof data);
res.end();
} catch (er) {
// uh oh! bad json!
res.statusCode = 400;
return res.end(`error: ${er.message}`);
}
});
});
server.listen(1337);
// $ curl localhost:1337 -d '{}'
// object
// $ curl localhost:1337 -d '"foo"'
// string
// $ curl localhost:1337 -d 'not json'
// error: Unexpected token o
</code></pre>
<h3>Class: stream.Duplex<span><a class="mark" href="#stream_class_stream_duplex" id="stream_class_stream_duplex">#</a></span></h3>
<p>Duplex streams are streams that implement both the <a href="#stream_class_stream_readable">Readable</a> and
<a href="#stream_class_stream_writable">Writable</a> interfaces.</p>
<p>Examples of Duplex streams include:</p>
<ul>
<li><a href="net.html#net_class_net_socket">TCP sockets</a></li>
<li><a href="zlib.html">zlib streams</a></li>
<li><a href="crypto.html">crypto streams</a></li>
</ul>
<h3>Class: stream.Readable<span><a class="mark" href="#stream_class_stream_readable" id="stream_class_stream_readable">#</a></span></h3>
<!--type=class-->
<p>The Readable stream interface is the abstraction for a <em>source</em> of
data that you are reading from. In other words, data comes <em>out</em> of a
Readable stream.</p>
<p>A Readable stream will not start emitting data until you indicate that
you are ready to receive it.</p>
<p>Readable streams have two "modes": a <strong>flowing mode</strong> and a <strong>paused
mode</strong>. When in flowing mode, data is read from the underlying system
and provided to your program as fast as possible. In paused mode, you
must explicitly call <a href="#stream_readable_read_size"><code>stream.read()</code></a> to get chunks of data out.
Streams start out in paused mode.</p>
<p><strong>Note</strong>: If no data event handlers are attached, and there are no
<a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a> destinations, and the stream is switched into flowing
mode, then data will be lost.</p>
<p>You can switch to flowing mode by doing any of the following:</p>
<ul>
<li>Adding a <a href="#stream_event_data"><code>'data'</code></a> event handler to listen for data.</li>
<li>Calling the <a href="#stream_readable_resume"><code>stream.resume()</code></a> method to explicitly open the
flow.</li>
<li>Calling the <a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a> method to send the data to a <a href="#stream_class_stream_writable">Writable</a>.</li>
</ul>
<p>You can switch back to paused mode by doing either of the following:</p>
<ul>
<li>If there are no pipe destinations, by calling the
<a href="#stream_readable_pause"><code>stream.pause()</code></a> method.</li>
<li>If there are pipe destinations, by removing any <a href="#stream_event_data"><code>'data'</code></a> event
handlers, and removing all pipe destinations by calling the
<a href="#stream_readable_unpipe_destination"><code>stream.unpipe()</code></a> method.</li>
</ul>
<p>Note that, for backwards compatibility reasons, removing <a href="#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="#stream_readable_pause"><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>Examples of readable streams include:</p>
<ul>
<li><a href="http.html#http_class_http_incomingmessage">HTTP responses, on the client</a></li>
<li><a href="http.html#http_class_http_incomingmessage">HTTP requests, on the server</a></li>
<li><a href="fs.html#fs_class_fs_readstream">fs read streams</a></li>
<li><a href="zlib.html">zlib streams</a></li>
<li><a href="crypto.html">crypto streams</a></li>
<li><a href="net.html#net_class_net_socket">TCP sockets</a></li>
<li><a href="child_process.html#child_process_child_stdout">child process stdout and stderr</a></li>
<li><a href="process.html#process_process_stdin"><code>process.stdin</code></a></li>
</ul>
<h4>Event: 'close'<span><a class="mark" href="#stream_event_close" id="stream_event_close">#</a></span></h4>
<p>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>Not all streams will emit the <code>'close'</code> event as the <code>'close'</code> event is
optional.</p>
<h4>Event: 'data'<span><a class="mark" href="#stream_event_data" id="stream_event_data">#</a></span></h4>
<div class="signature"><ul>
<li><code>chunk</code> <a href="buffer.html#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 chunk of data.</li>
</ul>
</div><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>If you just want to get all the data out of the stream as fast as
possible, this is the best way to do so.</p>
<pre><code class="lang-js">var readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
console.log('got %d bytes of data', chunk.length);
});
</code></pre>
<h4>Event: 'end'<span><a class="mark" href="#stream_event_end" id="stream_event_end">#</a></span></h4>
<p>This event fires when there will be no more data to read.</p>
<p>Note that the <code>'end'</code> event <strong>will not fire</strong> unless the data is
completely consumed. This can be done by switching into flowing mode,
or by calling <a href="#stream_readable_read_size"><code>stream.read()</code></a> repeatedly until you get to the
end.</p>
<pre><code class="lang-js">var readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
console.log('got %d bytes of data', chunk.length);
});
readable.on('end', () => {
console.log('there will be no more data.');
});
</code></pre>
<h4>Event: 'error'<span><a class="mark" href="#stream_event_error" id="stream_event_error">#</a></span></h4>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li>
</ul>
</div><p>Emitted if there was an error receiving data.</p>
<h4>Event: 'readable'<span><a class="mark" href="#stream_event_readable" id="stream_event_readable">#</a></span></h4>
<p>When a chunk of data can be read from the stream, it will emit a
<code>'readable'</code> event.</p>
<p>In some cases, listening for a <code>'readable'</code> event will cause some data
to be read into the internal buffer from the underlying system, if it
hadn't already.</p>
<pre><code class="lang-javascript">var readable = getReadableStreamSomehow();
readable.on('readable', () => {
// there is some data to read now
});
</code></pre>
<p>Once the internal buffer is drained, a <code>'readable'</code> event will fire
again when more data is available.</p>
<p>The <code>'readable'</code> event is not emitted in the "flowing" mode with the
sole exception of the last one, on end-of-stream.</p>
<p>The <code>'readable'</code> event indicates that the stream has new information:
either new data is available or the end of the stream has been reached.
In the former case, <a href="#stream_readable_read_size"><code>stream.read()</code></a> will return that data. In the
latter case, <a href="#stream_readable_read_size"><code>stream.read()</code></a> will return null. For instance, in
the following example, <code>foo.txt</code> is an empty file:</p>
<pre><code class="lang-js">const fs = require('fs');
var rr = fs.createReadStream('foo.txt');
rr.on('readable', () => {
console.log('readable:', rr.read());
});
rr.on('end', () => {
console.log('end');
});
</code></pre>
<p>The output of running this script is:</p>
<pre><code>$ node test.js
readable: null
end
</code></pre><h4>readable.isPaused()<span><a class="mark" href="#stream_readable_ispaused" id="stream_readable_ispaused">#</a></span></h4>
<div class="signature"><ul>
<li>Returns: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a></li>
</ul>
</div><p>This method returns whether or not the <code>readable</code> has been <strong>explicitly</strong>
paused by client code (using <a href="#stream_readable_pause"><code>stream.pause()</code></a> without a
corresponding <a href="#stream_readable_resume"><code>stream.resume()</code></a>).</p>
<pre><code class="lang-js">var readable = new stream.Readable
readable.isPaused() // === false
readable.pause()
readable.isPaused() // === true
readable.resume()
readable.isPaused() // === false
</code></pre>
<h4>readable.pause()<span><a class="mark" href="#stream_readable_pause" id="stream_readable_pause">#</a></span></h4>
<div class="signature"><ul>
<li>Returns: <code>this</code></li>
</ul>
</div><p>This method will cause a stream in flowing mode to stop emitting
<a href="#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="lang-js">var readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
console.log('got %d bytes of data', chunk.length);
readable.pause();
console.log('there will be no more data for 1 second');
setTimeout(() => {
console.log('now data will start flowing again');
readable.resume();
}, 1000);
});
</code></pre>
<h4>readable.pipe(destination[, options])<span><a class="mark" href="#stream_readable_pipe_destination_options" id="stream_readable_pipe_destination_options">#</a></span></h4>
<div class="signature"><ul>
<li><code>destination</code> <a href="stream.html#stream_class_stream_writable" 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. Default = <code>true</code></li>
</ul>
</li>
</ul>
</div><p>This method pulls all the data out of a readable stream, and writes it
to the supplied destination, automatically managing the flow so that
the destination is not overwhelmed by a fast readable stream.</p>
<p>Multiple destinations can be piped to safely.</p>
<pre><code class="lang-js">var readable = getReadableStreamSomehow();
var writable = fs.createWriteStream('file.txt');
// All the data from readable goes into 'file.txt'
readable.pipe(writable);
</code></pre>
<p>This function returns the destination stream, so you can set up pipe
chains like so:</p>
<pre><code class="lang-js">var r = fs.createReadStream('file.txt');
var z = zlib.createGzip();
var w = fs.createWriteStream('file.txt.gz');
r.pipe(z).pipe(w);
</code></pre>
<p>For example, emulating the Unix <code>cat</code> command:</p>
<pre><code class="lang-js">process.stdin.pipe(process.stdout);
</code></pre>
<p>By default <a href="#stream_writable_end_chunk_encoding_callback"><code>stream.end()</code></a> is called on the destination when the
source stream emits <a href="#stream_event_end"><code>'end'</code></a>, so that <code>destination</code> is no longer writable.
Pass <code>{ end: false }</code> as <code>options</code> to keep the destination stream open.</p>
<p>This keeps <code>writer</code> open so that "Goodbye" can be written at the
end.</p>
<pre><code class="lang-js">reader.pipe(writer, { end: false });
reader.on('end', () => {
writer.end('Goodbye\n');
});
</code></pre>
<p>Note that <a href="process.html#process_process_stderr"><code>process.stderr</code></a> and <a href="process.html#process_process_stdout"><code>process.stdout</code></a> are never closed until
the process exits, regardless of the specified options.</p>
<h4>readable.read([size])<span><a class="mark" href="#stream_readable_read_size" id="stream_readable_read_size">#</a></span></h4>
<div class="signature"><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>Return <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> | <a href="buffer.html#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>
</div><p>The <code>read()</code> method pulls some data out of the internal buffer and
returns it. If there is no data available, then it will return
<code>null</code>.</p>
<p>If you pass in a <code>size</code> argument, then it will return that many
bytes. If <code>size</code> bytes are not available, then it will return <code>null</code>,
unless we've ended, in which case it will return the data remaining
in the buffer.</p>
<p>If you do not specify a <code>size</code> argument, then it will return all the
data in the internal buffer.</p>
<p>This method should only be called in paused mode. In flowing mode,
this method is called automatically until the internal buffer is
drained.</p>
<pre><code class="lang-js">var readable = getReadableStreamSomehow();
readable.on('readable', () => {
var chunk;
while (null !== (chunk = readable.read())) {
console.log('got %d bytes of data', chunk.length);
}
});
</code></pre>
<p>If this method returns a data chunk, then it will also trigger the
emission of a <a href="#stream_event_data"><code>'data'</code></a> event.</p>
<p>Note that calling <a href="#stream_readable_read_size"><code>stream.read([size])</code></a> after the <a href="#stream_event_end"><code>'end'</code></a>
event has been triggered will return <code>null</code>. No runtime error will be raised.</p>
<h4>readable.resume()<span><a class="mark" href="#stream_readable_resume" id="stream_readable_resume">#</a></span></h4>
<div class="signature"><ul>
<li>Returns: <code>this</code></li>
</ul>
</div><p>This method will cause the readable stream to resume emitting <a href="#stream_event_data"><code>'data'</code></a>
events.</p>
<p>This method will switch the stream into flowing mode. If you do <em>not</em>
want to consume the data from a stream, but you <em>do</em> want to get to
its <a href="#stream_event_end"><code>'end'</code></a> event, you can call <a href="#stream_readable_resume"><code>stream.resume()</code></a> to open
the flow of data.</p>
<pre><code class="lang-js">var readable = getReadableStreamSomehow();
readable.resume();
readable.on('end', () => {
console.log('got to the end, but did not read anything');
});
</code></pre>
<h4>readable.setEncoding(encoding)<span><a class="mark" href="#stream_readable_setencoding_encoding" id="stream_readable_setencoding_encoding">#</a></span></h4>
<div class="signature"><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: <code>this</code></li>
</ul>
</div><p>Call this function to cause the stream to return strings of the specified
encoding instead of Buffer objects. For example, if you do
<code>readable.setEncoding('utf8')</code>, then the output data will be interpreted as
UTF-8 data, and returned as strings. If you do <code>readable.setEncoding('hex')</code>,
then the data will be encoded in hexadecimal string format.</p>
<p>This properly handles multi-byte characters that would otherwise be
potentially mangled if you simply pulled the Buffers directly and
called <a href="buffer.html#buffer_buf_tostring_encoding_start_end"><code>buf.toString(encoding)</code></a> on them. If you want to read the data
as strings, always use this method.</p>
<p>Also you can disable any encoding at all with <code>readable.setEncoding(null)</code>.
This approach is very useful if you deal with binary data or with large
multi-byte strings spread out over multiple chunks.</p>
<pre><code class="lang-js">var readable = getReadableStreamSomehow();
readable.setEncoding('utf8');
readable.on('data', (chunk) => {
assert.equal(typeof chunk, 'string');
console.log('got %d characters of string data', chunk.length);
});
</code></pre>
<h4>readable.unpipe([destination])<span><a class="mark" href="#stream_readable_unpipe_destination" id="stream_readable_unpipe_destination">#</a></span></h4>
<div class="signature"><ul>
<li><code>destination</code> <a href="stream.html#stream_class_stream_writable" class="type"><stream.Writable></a> Optional specific stream to unpipe</li>
</ul>
</div><p>This method will remove the hooks set up for a previous <a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a>
call.</p>
<p>If the destination is not specified, then all pipes are removed.</p>
<p>If the destination is specified, but no pipe is set up for it, then
this is a no-op.</p>
<pre><code class="lang-js">var readable = getReadableStreamSomehow();
var writable = fs.createWriteStream('file.txt');
// All the data from readable goes into 'file.txt',
// but only for the first second
readable.pipe(writable);
setTimeout(() => {
console.log('stop writing to file.txt');
readable.unpipe(writable);
console.log('manually close the file stream');
writable.end();
}, 1000);
</code></pre>
<h4>readable.unshift(chunk)<span><a class="mark" href="#stream_readable_unshift_chunk" id="stream_readable_unshift_chunk">#</a></span></h4>
<div class="signature"><ul>
<li><code>chunk</code> <a href="buffer.html#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> Chunk of data to unshift onto the read queue</li>
</ul>
</div><p>This is useful in certain cases where a stream is being consumed by a
parser, which needs to "un-consume" some data that it has
optimistically pulled out of the source, so that the stream can be
passed on to some other party.</p>
<p>Note that <code>stream.unshift(chunk)</code> cannot be called after the <a href="#stream_event_end"><code>'end'</code></a> event
has been triggered; a runtime error will be raised.</p>
<p>If you find that you must often call <code>stream.unshift(chunk)</code> in your
programs, consider implementing a <a href="#stream_class_stream_transform">Transform</a> stream instead. (See <a href="#stream_api_for_stream_implementors">API
for Stream Implementors</a>.)</p>
<pre><code class="lang-js">// Pull off a header delimited by \n\n
// use unshift() if we get too much
// Call the callback with (error, header, stream)
const StringDecoder = require('string_decoder').StringDecoder;
function parseHeader(stream, callback) {
stream.on('error', callback);
stream.on('readable', onReadable);
var decoder = new StringDecoder('utf8');
var header = '';
function onReadable() {
var chunk;
while (null !== (chunk = stream.read())) {
var str = decoder.write(chunk);
if (str.match(/\n\n/)) {
// found the header boundary
var split = str.split(/\n\n/);
header += split.shift();
var remaining = split.join('\n\n');
var buf = new Buffer(remaining, 'utf8');
if (buf.length)
stream.unshift(buf);
stream.removeListener('error', callback);
stream.removeListener('readable', onReadable);
// now the body of the message can be read from the stream.
callback(null, header, stream);
} else {
// still reading the header.
header += str;
}
}
}
}
</code></pre>
<p>Note that, unlike <a href="#stream_readable_push_chunk_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>unshift()</code> is called during a
read (i.e. from within a <a href="#stream_readable_read_size_1"><code>stream._read()</code></a> implementation on a
custom stream). Following the call to <code>unshift()</code> with an immediate
<a href="#stream_readable_push_chunk_encoding"><code>stream.push('')</code></a> will reset the reading state appropriately,
however it is best to simply avoid calling <code>unshift()</code> while in the process of
performing a read.</p>
<h4>readable.wrap(stream)<span><a class="mark" href="#stream_readable_wrap_stream" id="stream_readable_wrap_stream">#</a></span></h4>
<div class="signature"><ul>
<li><code>stream</code> <a href="stream.html#stream_stream" class="type"><Stream></a> An "old style" readable stream</li>
</ul>
</div><p>Versions of Node.js prior to v0.10 had streams that did not implement the
entire Streams API as it is today. (See <a href="#stream_compatibility_with_older_node_js_versions">Compatibility</a> for
more information.)</p>
<p>If you are using an older Node.js library that emits <a href="#stream_event_data"><code>'data'</code></a> events and
has a <a href="#stream_readable_pause"><code>stream.pause()</code></a> method that is advisory only, then you
can use the <code>wrap()</code> method to create a <a href="#stream_class_stream_readable">Readable</a> stream that uses the old
stream as its data source.</p>
<p>You will very rarely ever need to call this function, but it exists
as a convenience for interacting with old Node.js programs and libraries.</p>
<p>For example:</p>
<pre><code class="lang-js">const OldReader = require('./old-api-module.js').OldReader;
const Readable = require('stream').Readable;
const oreader = new OldReader;
const myReader = new Readable().wrap(oreader);
myReader.on('readable', () => {
myReader.read(); // etc.
});
</code></pre>
<h3>Class: stream.Transform<span><a class="mark" href="#stream_class_stream_transform" id="stream_class_stream_transform">#</a></span></h3>
<p>Transform streams are <a href="#stream_class_stream_duplex">Duplex</a> streams where the output is in some way
computed from the input. They implement both the <a href="#stream_class_stream_readable">Readable</a> and
<a href="#stream_class_stream_writable">Writable</a> interfaces.</p>
<p>Examples of Transform streams include:</p>
<ul>
<li><a href="zlib.html">zlib streams</a></li>
<li><a href="crypto.html">crypto streams</a></li>
</ul>
<h3>Class: stream.Writable<span><a class="mark" href="#stream_class_stream_writable" id="stream_class_stream_writable">#</a></span></h3>
<!--type=class-->
<p>The Writable stream interface is an abstraction for a <em>destination</em>
that you are writing data <em>to</em>.</p>
<p>Examples of writable streams include:</p>
<ul>
<li><a href="http.html#http_class_http_clientrequest">HTTP requests, on the client</a></li>
<li><a href="http.html#http_class_http_serverresponse">HTTP responses, on the server</a></li>
<li><a href="fs.html#fs_class_fs_writestream">fs write streams</a></li>
<li><a href="zlib.html">zlib streams</a></li>
<li><a href="crypto.html">crypto streams</a></li>
<li><a href="net.html#net_class_net_socket">TCP sockets</a></li>
<li><a href="child_process.html#child_process_child_stdin">child process stdin</a></li>
<li><a href="process.html#process_process_stdout"><code>process.stdout</code></a>, <a href="process.html#process_process_stderr"><code>process.stderr</code></a></li>
</ul>
<h4>Event: 'close'<span><a class="mark" href="#stream_event_close_1" id="stream_event_close_1">#</a></span></h4>
<p>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>Not all streams will emit the <code>'close'</code> event as the <code>'close'</code> event is
optional.</p>
<h4>Event: 'drain'<span><a class="mark" href="#stream_event_drain" id="stream_event_drain">#</a></span></h4>
<p>If a <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write(chunk)</code></a> call returns <code>false</code>, then the
<code>'drain'</code> event will indicate when it is appropriate to begin writing more data
to the stream.</p>
<pre><code class="lang-js">// Write the data to the supplied writable stream one million times.
// Be attentive to back-pressure.
function writeOneMillionTimes(writer, data, encoding, callback) {
var i = 1000000;
write();
function write() {
var ok = true;
do {
i -= 1;
if (i === 0) {
// last time!
writer.write(data, encoding, callback);
} else {
// see if we should continue, or wait
// don't pass the callback, because we're not done yet.
ok = writer.write(data, encoding);
}
} while (i > 0 && ok);
if (i > 0) {
// had to stop early!
// write some more once it drains
writer.once('drain', write);
}
}
}
</code></pre>
<h4>Event: 'error'<span><a class="mark" href="#stream_event_error_1" id="stream_event_error_1">#</a></span></h4>
<div class="signature"><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error" class="type"><Error></a></li>
</ul>
</div><p>Emitted if there was an error when writing or piping data.</p>
<h4>Event: 'finish'<span><a class="mark" href="#stream_event_finish" id="stream_event_finish">#</a></span></h4>
<p>When the <a href="#stream_writable_end_chunk_encoding_callback"><code>stream.end()</code></a> method has been called, and all data has
been flushed to the underlying system, this event is emitted.</p>
<pre><code class="lang-javascript">var writer = getWritableStreamSomehow();
for (var i = 0; i < 100; i ++) {
writer.write('hello, #${i}!\n');
}
writer.end('this is the end\n');
writer.on('finish', () => {
console.error('all writes are now complete.');
});
</code></pre>
<h4>Event: 'pipe'<span><a class="mark" href="#stream_event_pipe" id="stream_event_pipe">#</a></span></h4>
<div class="signature"><ul>
<li><code>src</code> <a href="stream.html#stream_class_stream_readable" class="type"><stream.Readable></a> source stream that is piping to this writable</li>
</ul>
</div><p>This is emitted whenever the <a href="#stream_readable_pipe_destination_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="lang-js">var writer = getWritableStreamSomehow();
var reader = getReadableStreamSomehow();
writer.on('pipe', (src) => {
console.error('something is piping into the writer');
assert.equal(src, reader);
});
reader.pipe(writer);
</code></pre>
<h4>Event: 'unpipe'<span><a class="mark" href="#stream_event_unpipe" id="stream_event_unpipe">#</a></span></h4>
<div class="signature"><ul>
<li><code>src</code> <span class="type"><<a href="#stream_class_stream_readable">Readable</a> Stream></span> The source stream that
<a href="#stream_readable_unpipe_destination">unpiped</a> this writable</li>
</ul>
</div><p>This is emitted whenever the <a href="#stream_readable_unpipe_destination"><code>stream.unpipe()</code></a> method is called on a
readable stream, removing this writable from its set of destinations.</p>
<pre><code class="lang-js">var writer = getWritableStreamSomehow();
var reader = getReadableStreamSomehow();
writer.on('unpipe', (src) => {
console.error('something has stopped piping into the writer');
assert.equal(src, reader);
});
reader.pipe(writer);
reader.unpipe(writer);
</code></pre>
<h4>writable.cork()<span><a class="mark" href="#stream_writable_cork" id="stream_writable_cork">#</a></span></h4>
<p>Forces buffering of all writes.</p>
<p>Buffered data will be flushed either at <a href="#stream_writable_uncork"><code>stream.uncork()</code></a> or at
<a href="#stream_writable_end_chunk_encoding_callback"><code>stream.end()</code></a> call.</p>
<h4>writable.end([chunk][, encoding][, callback])<span><a class="mark" href="#stream_writable_end_chunk_encoding_callback" id="stream_writable_end_chunk_encoding_callback">#</a></span></h4>
<div class="signature"><ul>
<li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> | <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> Optional data to write</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> Optional callback for when the stream is finished</li>
</ul>
</div><p>Call this method when no more data will be written to the stream. If supplied,
the callback is attached as a listener on the <a href="#stream_event_finish"><code>'finish'</code></a> event.</p>
<p>Calling <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a> after calling
<a href="#stream_writable_end_chunk_encoding_callback"><code>stream.end()</code></a> will raise an error.</p>
<pre><code class="lang-js">// write 'hello, ' and then end with 'world!'
var file = fs.createWriteStream('example.txt');
file.write('hello, ');
file.end('world!');
// writing more now is not allowed!
</code></pre>
<h4>writable.setDefaultEncoding(encoding)<span><a class="mark" href="#stream_writable_setdefaultencoding_encoding" id="stream_writable_setdefaultencoding_encoding">#</a></span></h4>
<div class="signature"><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>
</ul>
</div><p>Sets the default encoding for a writable stream.</p>
<h4>writable.uncork()<span><a class="mark" href="#stream_writable_uncork" id="stream_writable_uncork">#</a></span></h4>
<p>Flush all data, buffered since <a href="#stream_writable_cork"><code>stream.cork()</code></a> call.</p>
<h4>writable.write(chunk[, encoding][, callback])<span><a class="mark" href="#stream_writable_write_chunk_encoding_callback" id="stream_writable_write_chunk_encoding_callback">#</a></span></h4>
<div class="signature"><ul>
<li><code>chunk</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type" class="type"><String></a> | <a href="buffer.html#buffer_class_buffer" class="type"><Buffer></a> The data to write</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 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>true</code> if the data was handled completely.</li>
</ul>
</div><p>This method writes some data to the underlying system, and calls the
supplied callback once the data has been fully handled. If an error
occurs, the callback may or may not be called with the error as its
first argument. To detect write errors, listen for the <code>'error'</code> event.</p>
<p>The return value indicates if you should continue writing right now.
If the data had to be buffered internally, then it will return
<code>false</code>. Otherwise, it will return <code>true</code>.</p>
<p>This return value is strictly advisory. You MAY continue to write,
even if it returns <code>false</code>. However, writes will be buffered in
memory, so it is best not to do this excessively. Instead, wait for
the <a href="#stream_event_drain"><code>'drain'</code></a> event before writing more data.</p>
<h2>API for Stream Implementors<span><a class="mark" href="#stream_api_for_stream_implementors" id="stream_api_for_stream_implementors">#</a></span></h2>
<!--type=misc-->
<p>To implement any sort of stream, the pattern is the same:</p>
<ol>
<li>Extend the appropriate parent class in your own subclass. (The
<a href="util.html#util_util_inherits_constructor_superconstructor"><code>util.inherits()</code></a> method is particularly helpful for this.)</li>
<li>Call the appropriate parent class constructor in your constructor,
to be sure that the internal mechanisms are set up properly.</li>
<li>Implement one or more specific methods, as detailed below.</li>
</ol>
<p>The class to extend and the method(s) to implement depend on the sort
of stream class you are writing:</p>
<table>
<thead>
<tr>
<th>
<p>Use-case</p>
</th>
<th>
<p>Class</p>
</th>
<th>
<p>Method(s) to implement</p>
</th>
</tr>
</thead>
<tr>
<td>
<p>Reading only</p>
</td>
<td>
<p><a href="#stream_class_stream_readable_1">Readable</a></p>
</td>
<td>
<p><code><a href="#stream_readable_read_size_1">_read</a></code></p>
</td>
</tr>
<tr>
<td>
<p>Writing only</p>
</td>
<td>
<p><a href="#stream_class_stream_writable_1">Writable</a></p>
</td>
<td>
<p><code><a href="#stream_writable_write_chunk_encoding_callback_1">_write</a></code>, <code><a href="#stream_writable_writev_chunks_callback">_writev</a></code></p>
</td>
</tr>
<tr>
<td>
<p>Reading and writing</p>
</td>
<td>
<p><a href="#stream_class_stream_duplex_1">Duplex</a></p>
</td>
<td>
<p><code><a href="#stream_readable_read_size_1">_read</a></code>, <code><a href="#stream_writable_write_chunk_encoding_callback_1">_write</a></code>, <code><a href="#stream_writable_writev_chunks_callback">_writev</a></code></p>
</td>
</tr>
<tr>
<td>
<p>Operate on written data, then read the result</p>
</td>
<td>
<p><a href="#stream_class_stream_transform_1">Transform</a></p>
</td>
<td>
<p><code><a href="#stream_transform_transform_chunk_encoding_callback">_transform</a></code>, <code><a href="#stream_transform_flush_callback">_flush</a></code></p>
</td>
</tr>
</table>
<p>In your implementation code, it is very important to never call the methods
described in <a href="#stream_api_for_stream_consumers">API for Stream Consumers</a>. Otherwise, you can potentially cause
adverse side effects in programs that consume your streaming interfaces.</p>
<h3>Class: stream.Duplex<span><a class="mark" href="#stream_class_stream_duplex_1" id="stream_class_stream_duplex_1">#</a></span></h3>
<!--type=class-->
<p>A "duplex" stream is one that is both Readable and Writable, such as a TCP
socket connection.</p>
<p>Note that <code>stream.Duplex</code> is an abstract class designed to be extended
with an underlying implementation of the <a href="#stream_readable_read_size_1"><code>stream._read(size)</code></a>
and <a href="#stream_writable_write_chunk_encoding_callback_1"><code>stream._write(chunk, encoding, callback)</code></a> methods as you
would with a Readable or Writable stream class.</p>
<p>Since JavaScript doesn't have multiple prototypal inheritance, this class
prototypally inherits from Readable, and then parasitically from Writable. It is
thus up to the user to implement both the low-level
<a href="#stream_readable_read_size_1"><code>stream._read(n)</code></a> method as well as the low-level
<a href="#stream_writable_write_chunk_encoding_callback_1"><code>stream._write(chunk, encoding, callback)</code></a> method on extension
duplex classes.</p>
<h4>new stream.Duplex(options)<span><a class="mark" href="#stream_new_stream_duplex_options" id="stream_new_stream_duplex_options">#</a></span></h4>
<div class="signature"><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 Writable and Readable
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> Default = <code>true</code>. If set to <code>false</code>, then
the stream will automatically end the readable side when the
writable side ends and vice versa.</li>
<li><code>readableObjectMode</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Default = <code>false</code>. Sets <code>objectMode</code>
for readable side of the stream. Has no effect if <code>objectMode</code>
is <code>true</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> Default = <code>false</code>. Sets <code>objectMode</code>
for writable side of the stream. Has no effect if <code>objectMode</code>
is <code>true</code>.</li>
</ul>
</li>
</ul>
</div><p>In classes that extend the Duplex class, make sure to call the
constructor so that the buffering settings can be properly
initialized.</p>
<h3>Class: stream.PassThrough<span><a class="mark" href="#stream_class_stream_passthrough" id="stream_class_stream_passthrough">#</a></span></h3>
<p>This is a trivial implementation of a <a href="#stream_class_stream_transform">Transform</a> stream that simply
passes the input bytes across to the output. Its purpose is mainly
for examples and testing, but there are occasionally use cases where
it can come in handy as a building block for novel sorts of streams.</p>
<h3>Class: stream.Readable<span><a class="mark" href="#stream_class_stream_readable_1" id="stream_class_stream_readable_1">#</a></span></h3>
<!--type=class-->
<p><code>stream.Readable</code> is an abstract class designed to be extended with an
underlying implementation of the <a href="#stream_readable_read_size_1"><code>stream._read(size)</code></a> method.</p>
<p>Please see <a href="#stream_api_for_stream_consumers">API for Stream Consumers</a> for how to consume
streams in your programs. What follows is an explanation of how to
implement Readable streams in your programs.</p>
<h4>new stream.Readable(<a href="#zlib_class_options">options</a>)<span><a class="mark" href="#stream_new_stream_readable_options" id="stream_new_stream_readable_options">#</a></span></h4>
<div class="signature"><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 number of bytes to store in
the internal buffer before ceasing to read from the underlying
resource. Default = <code>16384</code> (16kb), 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. Default = <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="#stream_readable_read_size"><code>stream.read(n)</code></a> returns
a single value instead of a Buffer of size n. Default = <code>false</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="#stream_readable_read_size_1"><code>stream._read()</code></a>
method.</li>
</ul>
</li>
</ul>
</div><p>In classes that extend the Readable class, make sure to call the
Readable constructor so that the buffering settings can be properly
initialized.</p>
<h4>readable._read(size)<span><a class="mark" href="#stream_readable_read_size_1" id="stream_readable_read_size_1">#</a></span></h4>
<div class="signature"><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>
</div><p>Note: <strong>Implement this method, but do NOT call it directly.</strong></p>
<p>This method is prefixed with an underscore because it is internal to the
class that defines it and should only be called by the internal Readable
class methods. All Readable stream implementations must provide a _read
method to fetch data from the underlying resource.</p>
<p>When <code>_read()</code> is called, if data is available from the resource, the <code>_read()</code>
implementation should start pushing that data into the read queue by calling
<a href="#stream_readable_push_chunk_encoding"><code>this.push(dataChunk)</code></a>. <code>_read()</code> should continue reading from
the resource and pushing data until push returns <code>false</code>, at which point it
should stop reading from the resource. Only when <code>_read()</code> is called again after
it has stopped should it start reading more data from the resource and pushing
that data onto the queue.</p>
<p>Note: once the <code>_read()</code> method is called, it will not be called again until
the <a href="#stream_readable_push_chunk_encoding"><code>stream.push()</code></a> method is called.</p>
<p>The <code>size</code> argument is advisory. Implementations where a "read" is a
single call that returns data can use this to know how much data to
fetch. Implementations where that is not relevant, such as TCP or
TLS, may ignore this argument, and simply provide data whenever it
becomes available. There is no need, for example to "wait" until
<code>size</code> bytes are available before calling <a href="#stream_readable_push_chunk_encoding"><code>stream.push(chunk)</code></a>.</p>
<h4>readable.push(chunk[, encoding])<span><a class="mark" href="#stream_readable_push_chunk_encoding" id="stream_readable_push_chunk_encoding">#</a></span></h4>
<div class="signature"><ul>
<li><code>chunk</code> <a href="buffer.html#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#String_type" class="type"><String></a> Chunk of data to push into the read queue</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
Buffer encoding, such as <code>'utf8'</code> or <code>'ascii'</code></li>
<li>return <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type" class="type"><Boolean></a> Whether or not more pushes should be performed</li>
</ul>
</div><p>Note: <strong>This method should be called by Readable implementors, NOT
by consumers of Readable streams.</strong></p>
<p>If a value other than null is passed, The <code>push()</code> method adds a chunk of data
into the queue for subsequent stream processors to consume. If <code>null</code> is
passed, it signals the end of the stream (EOF), after which no more data
can be written.</p>
<p>The data added with <code>push()</code> can be pulled out by calling the
<a href="#stream_readable_read_size"><code>stream.read()</code></a> method when the <a href="#stream_event_readable"><code>'readable'</code></a> event fires.</p>
<p>This API is designed to be as flexible as possible. For example,
you may be wrapping a lower-level source which has some sort of
pause/resume mechanism, and a data callback. In those cases, you
could wrap the low-level source object by doing something like this:</p>
<pre><code class="lang-js">// source is an object with readStop() and readStart() methods,
// and an `ondata` member that gets called when it has data, and
// an `onend` member that gets called when the data is over.
util.inherits(SourceWrapper, Readable);
function SourceWrapper(options) {
Readable.call(this, options);
this._source = getLowlevelSourceObject();
// Every time there's data, we push it into the internal buffer.
this._source.ondata = (chunk) => {
// if push() returns false, then we need to stop reading from source
if (!this.push(chunk))
this._source.readStop();
};
// When the source ends, we push the EOF-signaling `null` chunk
this._source.onend = () => {
this.push(null);
};
}
// _read will be called when the stream wants to pull more data in
// the advisory size argument is ignored in this case.
SourceWrapper.prototype._read = function(size) {
this._source.readStart();
};
</code></pre>
<h4>Example: A Counting Stream<span><a class="mark" href="#stream_example_a_counting_stream" id="stream_example_a_counting_stream">#</a></span></h4>
<!--type=example-->
<p>This is a basic example of a Readable stream. It emits the numerals
from 1 to 1,000,000 in ascending order, and then ends.</p>
<pre><code class="lang-js">const Readable = require('stream').Readable;
const util = require('util');
util.inherits(Counter, Readable);
function Counter(opt) {
Readable.call(this, opt);
this._max = 1000000;
this._index = 1;
}
Counter.prototype._read = function() {
var i = this._index++;
if (i > this._max)
this.push(null);
else {
var str = '' + i;
var buf = new Buffer(str, 'ascii');
this.push(buf);
}
};
</code></pre>
<h4>Example: SimpleProtocol v1 (Sub-optimal)<span><a class="mark" href="#stream_example_simpleprotocol_v1_sub_optimal" id="stream_example_simpleprotocol_v1_sub_optimal">#</a></span></h4>
<p>This is similar to the <code>parseHeader</code> function described
<a href="#stream_readable_unshift_chunk">here</a>, but implemented as a custom stream.
Also, note that this implementation does not convert the incoming data to a
string.</p>
<p>However, this would be better implemented as a <a href="#stream_class_stream_transform">Transform</a> stream. See
<a href="#stream_example_simpleprotocol_parser_v2">SimpleProtocol v2</a> for a better implementation.</p>
<pre><code class="lang-js">// A parser for a simple data protocol.
// The "header" is a JSON object, followed by 2 \n characters, and
// then a message body.
//
// NOTE: This can be done more simply as a Transform stream!
// Using Readable directly for this is sub-optimal. See the
// alternative example below under the Transform section.
const Readable = require('stream').Readable;
const util = require('util');
util.inherits(SimpleProtocol, Readable);
function SimpleProtocol(source, options) {
if (!(this instanceof SimpleProtocol))
return new SimpleProtocol(source, options);
Readable.call(this, options);
this._inBody = false;
this._sawFirstCr = false;
// source is a readable stream, such as a socket or file
this._source = source;
source.on('end', () => {
this.push(null);
});
// give it a kick whenever the source is readable
// read(0) will not consume any bytes
source.on('readable', () => {
this.read(0);
});
this._rawHeader = [];
this.header = null;
}
SimpleProtocol.prototype._read = function(n) {
if (!this._inBody) {
var chunk = this._source.read();
// if the source doesn't have data, we don't have data yet.
if (chunk === null)
return this.push('');
// check if the chunk has a \n\n
var split = -1;
for (var i = 0; i < chunk.length; i++) {
if (chunk[i] === 10) { // '\n'
if (this._sawFirstCr) {
split = i;
break;
} else {
this._sawFirstCr = true;
}
} else {
this._sawFirstCr = false;
}
}
if (split === -1) {
// still waiting for the \n\n
// stash the chunk, and try again.
this._rawHeader.push(chunk);
this.push('');
} else {
this._inBody = true;
var h = chunk.slice(0, split);
this._rawHeader.push(h);
var header = Buffer.concat(this._rawHeader).toString();
try {
this.header = JSON.parse(header);
} catch (er) {
this.emit('error', new Error('invalid simple protocol data'));
return;
}
// now, because we got some extra data, unshift the rest
// back into the read queue so that our consumer will see it.
var b = chunk.slice(split);
this.unshift(b);
// calling unshift by itself does not reset the reading state
// of the stream; since we're inside _read, doing an additional
// push('') will reset the state appropriately.
this.push('');
// and let them know that we are done parsing the header.
this.emit('header', this.header);
}
} else {
// from there on, just provide the data to our consumer.
// careful not to push(null), since that would indicate EOF.
var chunk = this._source.read();
if (chunk) this.push(chunk);
}
};
// Usage:
// var parser = new SimpleProtocol(source);
// Now parser is a readable stream that will emit 'header'
// with the parsed header data.
</code></pre>
<h3>Class: stream.Transform<span><a class="mark" href="#stream_class_stream_transform_1" id="stream_class_stream_transform_1">#</a></span></h3>
<p>A "transform" stream is a duplex stream where the output is causally
connected in some way to the input, such as a <a href="zlib.html">zlib</a> stream or a
<a href="crypto.html">crypto</a> stream.</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
Hash stream will only ever have a single chunk of output which is
provided when the input is ended. A zlib stream will produce output
that is either much smaller or much larger than its input.</p>
<p>Rather than implement the <a href="#stream_readable_read_size_1"><code>stream._read()</code></a> and
<a href="#stream_writable_write_chunk_encoding_callback_1"><code>stream._write()</code></a> methods, Transform classes must implement the
<a href="#stream_transform_transform_chunk_encoding_callback"><code>stream._transform()</code></a> method, and may optionally
also implement the <a href="#stream_transform_flush_callback"><code>stream._flush()</code></a> method. (See below.)</p>
<h4>new stream.Transform(<a href="#zlib_class_options">options</a>)<span><a class="mark" href="#stream_new_stream_transform_options" id="stream_new_stream_transform_options">#</a></span></h4>
<div class="signature"><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 Writable and Readable
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="#stream_transform_transform_chunk_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="#stream_transform_flush_callback"><code>stream._flush()</code></a>
method.</li>
</ul>
</li>
</ul>
</div><p>In classes that extend the Transform class, make sure to call the
constructor so that the buffering settings can be properly
initialized.</p>
<h4>Events: 'finish' and 'end'<span><a class="mark" href="#stream_events_finish_and_end" id="stream_events_finish_and_end">#</a></span></h4>
<p>The <a href="#stream_event_finish"><code>'finish'</code></a> and <a href="#stream_event_end"><code>'end'</code></a> events are from the parent Writable
and Readable classes respectively. The <code>'finish'</code> event is fired after
<a href="#stream_writable_end_chunk_encoding_callback"><code>stream.end()</code></a> is called and all chunks have been processed by
<a href="#stream_transform_transform_chunk_encoding_callback"><code>stream._transform()</code></a>, <code>'end'</code> is fired after all data has
been output which is after the callback in <a href="#stream_transform_flush_callback"><code>stream._flush()</code></a>
has been called.</p>
<h4>transform._flush(callback)<span><a class="mark" href="#stream_transform_flush_callback" id="stream_transform_flush_callback">#</a></span></h4>
<div class="signature"><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 you are done flushing any remaining data.</li>
</ul>
</div><p>Note: <strong>This function MUST NOT be called directly.</strong> It MAY be implemented
by child classes, and if so, will be called by the internal Transform
class methods only.</p>
<p>In some cases, your transform operation may need to emit a bit more
data at the end of the stream. For example, a <code>Zlib</code> compression
stream will store up some internal state so that it can optimally
compress the output. At the end, however, it needs to do the best it
can with what is left, so that the data will be complete.</p>
<p>In those cases, you can implement a <code>_flush()</code> method, which will be
called at the very end, after all the written data is consumed, but
before emitting <a href="#stream_event_end"><code>'end'</code></a> to signal the end of the readable side. Just
like with <a href="#stream_transform_transform_chunk_encoding_callback"><code>stream._transform()</code></a>, call
<code>transform.push(chunk)</code> zero or more times, as appropriate, and call <code>callback</code>
when the flush operation is complete.</p>
<p>This method is prefixed with an underscore because it is internal to
the class that defines it, and should not be called directly by user
programs. However, you <strong>are</strong> expected to override this method in
your own extension classes.</p>
<h4>transform._transform(chunk, encoding, callback)<span><a class="mark" href="#stream_transform_transform_chunk_encoding_callback" id="stream_transform_transform_chunk_encoding_callback">#</a></span></h4>
<div class="signature"><ul>
<li><code>chunk</code> <a href="buffer.html#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 chunk to be transformed. Will <strong>always</strong>
be a buffer unless the <code>decodeStrings</code> option was set to <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> If the chunk is a string, then this is the
encoding type. If chunk is a buffer, then this is the special
value - 'buffer', ignore it in this case.</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 and data) when you are done processing the supplied chunk.</li>
</ul>
</div><p>Note: <strong>This function MUST NOT be called directly.</strong> It should be
implemented by child classes, and called by the internal Transform
class methods only.</p>
<p>All Transform stream implementations must provide a <code>_transform()</code>
method to accept input and produce output.</p>
<p><code>_transform()</code> should do whatever has to be done in this specific
Transform class, to handle the bytes being written, and pass them off
to the readable portion of the interface. Do asynchronous I/O,
process things, and so on.</p>
<p>Call <code>transform.push(outputChunk)</code> 0 or more times to generate output
from this input chunk, depending on how much data you want to output
as a result of this chunk.</p>
<p>Call the callback function only when the current chunk is completely
consumed. Note that there may or may not be output as a result of any
particular input chunk. If you supply a second argument to the callback
it will be passed to the push method. In other words the following are
equivalent:</p>
<pre><code class="lang-js">transform.prototype._transform = function (data, encoding, callback) {
this.push(data);
callback();
};
transform.prototype._transform = function (data, encoding, callback) {
callback(null, data);
};
</code></pre>
<p>This method is prefixed with an underscore because it is internal to
the class that defines it, and should not be called directly by user
programs. However, you <strong>are</strong> expected to override this method in
your own extension classes.</p>
<h4>Example: <code>SimpleProtocol</code> parser v2<span><a class="mark" href="#stream_example_simpleprotocol_parser_v2" id="stream_example_simpleprotocol_parser_v2">#</a></span></h4>
<p>The example <a href="#stream_example_simpleprotocol_v1_sub_optimal">here</a> of a simple
protocol parser can be implemented simply by using the higher level
<a href="#stream_class_stream_transform">Transform</a> stream class, similar to the <code>parseHeader</code> and <code>SimpleProtocol
v1</code> examples.</p>
<p>In this example, rather than providing the input as an argument, it
would be piped into the parser, which is a more idiomatic Node.js stream
approach.</p>
<pre><code class="lang-javascript">const util = require('util');
const Transform = require('stream').Transform;
util.inherits(SimpleProtocol, Transform);
function SimpleProtocol(options) {
if (!(this instanceof SimpleProtocol))
return new SimpleProtocol(options);
Transform.call(this, options);
this._inBody = false;
this._sawFirstCr = false;
this._rawHeader = [];
this.header = null;
}
SimpleProtocol.prototype._transform = function(chunk, encoding, done) {
if (!this._inBody) {
// check if the chunk has a \n\n
var split = -1;
for (var i = 0; i < chunk.length; i++) {
if (chunk[i] === 10) { // '\n'
if (this._sawFirstCr) {
split = i;
break;
} else {
this._sawFirstCr = true;
}
} else {
this._sawFirstCr = false;
}
}
if (split === -1) {
// still waiting for the \n\n
// stash the chunk, and try again.
this._rawHeader.push(chunk);
} else {
this._inBody = true;
var h = chunk.slice(0, split);
this._rawHeader.push(h);
var header = Buffer.concat(this._rawHeader).toString();
try {
this.header = JSON.parse(header);
} catch (er) {
this.emit('error', new Error('invalid simple protocol data'));
return;
}
// and let them know that we are done parsing the header.
this.emit('header', this.header);
// now, because we got some extra data, emit this first.
this.push(chunk.slice(split));
}
} else {
// from there on, just provide the data to our consumer as-is.
this.push(chunk);
}
done();
};
// Usage:
// var parser = new SimpleProtocol();
// source.pipe(parser)
// Now parser is a readable stream that will emit 'header'
// with the parsed header data.
</code></pre>
<h3>Class: stream.Writable<span><a class="mark" href="#stream_class_stream_writable_1" id="stream_class_stream_writable_1">#</a></span></h3>
<!--type=class-->
<p><code>stream.Writable</code> is an abstract class designed to be extended with an
underlying implementation of the
<a href="#stream_writable_write_chunk_encoding_callback_1"><code>stream._write(chunk, encoding, callback)</code></a> method.</p>
<p>Please see <a href="#stream_api_for_stream_consumers">API for Stream Consumers</a> for how to consume
writable streams in your programs. What follows is an explanation of
how to implement Writable streams in your programs.</p>
<h4>new stream.Writable(<a href="#zlib_class_options">options</a>)<span><a class="mark" href="#stream_new_stream_writable_options" id="stream_new_stream_writable_options">#</a></span></h4>
<div class="signature"><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="#stream_writable_write_chunk_encoding_callback"><code>stream.write()</code></a> starts returning <code>false</code>. Default = <code>16384</code>
(16kb), 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 or not to decode strings into
Buffers before passing them to <a href="#stream_writable_write_chunk_encoding_callback_1"><code>stream._write()</code></a>.
Default = <code>true</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="#stream_writable_write_chunk_encoding_callback"><code>stream.write(anyObj)</code></a> is a valid operation. If set you can
write arbitrary data instead of only <code>Buffer</code> / <code>String</code> data.
Default = <code>false</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="#stream_writable_write_chunk_encoding_callback_1"><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="#stream_writable_writev_chunks_callback"><code>stream._writev()</code></a> method.</li>
</ul>
</li>
</ul>
</div><p>In classes that extend the Writable class, make sure to call the
constructor so that the buffering settings can be properly
initialized.</p>
<h4>writable._write(chunk, encoding, callback)<span><a class="mark" href="#stream_writable_write_chunk_encoding_callback_1" id="stream_writable_write_chunk_encoding_callback_1">#</a></span></h4>
<div class="signature"><ul>
<li><code>chunk</code> <a href="buffer.html#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 chunk to be written. Will <strong>always</strong>
be a buffer unless the <code>decodeStrings</code> option was set to <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> If the chunk is a string, then this is the
encoding type. If chunk is a buffer, then this is the special
value - 'buffer', ignore it in this case.</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 you are done processing the supplied chunk.</li>
</ul>
</div><p>All Writable stream implementations must provide a
<a href="#stream_writable_write_chunk_encoding_callback_1"><code>stream._write()</code></a> method to send data to the underlying
resource.</p>
<p>Note: <strong>This function MUST NOT be called directly.</strong> It should be
implemented by child classes, and called by the internal Writable
class methods only.</p>
<p>Call the callback using the standard <code>callback(error)</code> pattern to
signal that the write completed successfully or with an error.</p>
<p>If the <code>decodeStrings</code> flag is set in the constructor options, then
<code>chunk</code> may be a string rather than a Buffer, and <code>encoding</code> will
indicate the sort of string that it is. This is to support
implementations that have an optimized handling for certain string
data encodings. If you do not explicitly set the <code>decodeStrings</code>
option to <code>false</code>, then you can safely ignore the <code>encoding</code> argument,
and assume that <code>chunk</code> will always be a Buffer.</p>
<p>This method is prefixed with an underscore because it is internal to
the class that defines it, and should not be called directly by user
programs. However, you <strong>are</strong> expected to override this method in
your own extension classes.</p>
<h4>writable._writev(chunks, callback)<span><a class="mark" href="#stream_writable_writev_chunks_callback" id="stream_writable_writev_chunks_callback">#</a></span></h4>
<div class="signature"><ul>
<li><code>chunks</code> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" class="type"><Array></a> The chunks to be written. Each chunk has following
format: <code>{ chunk: ..., encoding: ... }</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> Call this function (optionally with an error
argument) when you are done processing the supplied chunks.</li>
</ul>
</div><p>Note: <strong>This function MUST NOT be called directly.</strong> It may be
implemented by child classes, and called by the internal Writable
class methods only.</p>
<p>This function is completely optional to implement. In most cases it is
unnecessary. If implemented, it will be called with all the chunks
that are buffered in the write queue.</p>
<h2>Simplified Constructor API<span><a class="mark" href="#stream_simplified_constructor_api" id="stream_simplified_constructor_api">#</a></span></h2>
<!--type=misc-->
<p>In simple cases there is now the added benefit of being able to construct a
stream without inheritance.</p>
<p>This can be done by passing the appropriate methods as constructor options:</p>
<p>Examples:</p>
<h3>Duplex<span><a class="mark" href="#stream_duplex" id="stream_duplex">#</a></span></h3>
<pre><code class="lang-js">var duplex = new stream.Duplex({
read: function(n) {
// sets this._read under the hood
// push data onto the read queue, passing null
// will signal the end of the stream (EOF)
this.push(chunk);
},
write: function(chunk, encoding, next) {
// sets this._write under the hood
// An optional error can be passed as the first argument
next()
}
});
// or
var duplex = new stream.Duplex({
read: function(n) {
// sets this._read under the hood
// push data onto the read queue, passing null
// will signal the end of the stream (EOF)
this.push(chunk);
},
writev: function(chunks, next) {
// sets this._writev under the hood
// An optional error can be passed as the first argument
next()
}
});
</code></pre>
<h3>Readable<span><a class="mark" href="#stream_readable" id="stream_readable">#</a></span></h3>
<pre><code class="lang-js">var readable = new stream.Readable({
read: function(n) {
// sets this._read under the hood
// push data onto the read queue, passing null
// will signal the end of the stream (EOF)
this.push(chunk);
}
});
</code></pre>
<h3>Transform<span><a class="mark" href="#stream_transform" id="stream_transform">#</a></span></h3>
<pre><code class="lang-js">var transform = new stream.Transform({
transform: function(chunk, encoding, next) {
// sets this._transform under the hood
// generate output as many times as needed
// this.push(chunk);
// call when the current chunk is consumed
next();
},
flush: function(done) {
// sets this._flush under the hood
// generate output as many times as needed
// this.push(chunk);
done();
}
});
</code></pre>
<h3>Writable<span><a class="mark" href="#stream_writable" id="stream_writable">#</a></span></h3>
<pre><code class="lang-js">var writable = new stream.Writable({
write: function(chunk, encoding, next) {
// sets this._write under the hood
// An optional error can be passed as the first argument
next()
}
});
// or
var writable = new stream.Writable({
writev: function(chunks, next) {
// sets this._writev under the hood
// An optional error can be passed as the first argument
next()
}
});
</code></pre>
<h2>Streams: Under the Hood<span><a class="mark" href="#stream_streams_under_the_hood" id="stream_streams_under_the_hood">#</a></span></h2>
<!--type=misc-->
<h3>Buffering<span><a class="mark" href="#stream_buffering" id="stream_buffering">#</a></span></h3>
<!--type=misc-->
<p>Both Writable and Readable streams will buffer data on an internal
object which can be retrieved from <code>_writableState.getBuffer()</code> or
<code>_readableState.buffer</code>, respectively.</p>
<p>The amount of data that will potentially be buffered depends on the
<code>highWaterMark</code> option which is passed into the constructor.</p>
<p>Buffering in Readable streams happens when the implementation calls
<a href="#stream_readable_push_chunk_encoding"><code>stream.push(chunk)</code></a>. If the consumer of the Stream does not
call <a href="#stream_readable_read_size"><code>stream.read()</code></a>, then the data will sit in the internal
queue until it is consumed.</p>
<p>Buffering in Writable streams happens when the user calls
<a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write(chunk)</code></a> repeatedly, even when it returns <code>false</code>.</p>
<p>The purpose of streams, especially with the <a href="#stream_readable_pipe_destination_options"><code>stream.pipe()</code></a> method, is to
limit the buffering of data to acceptable levels, so that sources and
destinations of varying speed will not overwhelm the available memory.</p>
<h3>Compatibility with Older Node.js Versions<span><a class="mark" href="#stream_compatibility_with_older_node_js_versions" id="stream_compatibility_with_older_node_js_versions">#</a></span></h3>
<!--type=misc-->
<p>In versions of Node.js prior to v0.10, the Readable stream interface was
simpler, but also less powerful and less useful.</p>
<ul>
<li>Rather than waiting for you to call the <a href="#stream_readable_read_size"><code>stream.read()</code></a> method,
<a href="#stream_event_data"><code>'data'</code></a> events would start emitting immediately. If you needed to do
some I/O to decide how to handle data, then you had to store the chunks
in some kind of buffer so that they would not be lost.</li>
<li>The <a href="#stream_readable_pause"><code>stream.pause()</code></a> method was advisory, rather than
guaranteed. This meant that you still had to be prepared to receive
<a href="#stream_event_data"><code>'data'</code></a> events even when the stream was in a paused state.</li>
</ul>
<p>In Node.js v0.10, the <a href="#stream_class_stream_readable">Readable</a> class was added.
For backwards compatibility with older Node.js programs, Readable streams
switch into "flowing mode" when a <a href="#stream_event_data"><code>'data'</code></a> event handler is added, or
when the <a href="#stream_readable_resume"><code>stream.resume()</code></a> method is called. The effect is
that, even if you are not using the new <a href="#stream_readable_read_size"><code>stream.read()</code></a> method
and <a href="#stream_event_readable"><code>'readable'</code></a> event, you no longer have to worry about losing
<a href="#stream_event_data"><code>'data'</code></a> chunks.</p>
<p>Most programs will continue to function normally. However, this
introduces an edge case in the following conditions:</p>
<ul>
<li>No <a href="#stream_event_data"><code>'data'</code></a> event handler is added.</li>
<li>The <a href="#stream_readable_resume"><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="lang-js">// WARNING! BROKEN!
net.createServer((socket) => {
// we add an 'end' method, but never consume the data
socket.on('end', () => {
// It will never get here.
socket.end('I got your message (but didnt read it)\n');
});
}).listen(1337);
</code></pre>
<p>In versions of Node.js prior to v0.10, the incoming message data would be
simply discarded. However, in Node.js v0.10 and beyond,
the socket will remain paused forever.</p>
<p>The workaround in this situation is to call the
<a href="#stream_readable_resume"><code>stream.resume()</code></a> method to start the flow of data:</p>
<pre><code class="lang-js">// Workaround
net.createServer((socket) => {
socket.on('end', () => {
socket.end('I got your message (but didnt read it)\n');
});
// start the flow of data, discarding it.
socket.resume();
}).listen(1337);
</code></pre>
<p>In addition to new Readable streams switching into flowing mode,
pre-v0.10 style streams can be wrapped in a Readable class using the
<a href="#stream_readable_wrap_stream"><code>stream.wrap()</code></a> method.</p>
<h3>Object Mode<span><a class="mark" href="#stream_object_mode" id="stream_object_mode">#</a></span></h3>
<!--type=misc-->
<p>Normally, Streams operate on Strings and Buffers exclusively.</p>
<p>Streams that are in <strong>object mode</strong> can emit generic JavaScript values
other than Buffers and Strings.</p>
<p>A Readable stream in object mode will always return a single item from
a call to <a href="#stream_readable_read_size"><code>stream.read(size)</code></a>, regardless of what the size
argument is.</p>
<p>A Writable stream in object mode will always ignore the <code>encoding</code>
argument to <a href="#stream_writable_write_chunk_encoding_callback"><code>stream.write(data, encoding)</code></a>.</p>
<p>The special value <code>null</code> still retains its special value for object
mode streams. That is, for object mode readable streams, <code>null</code> as a
return value from <a href="#stream_readable_read_size"><code>stream.read()</code></a> indicates that there is no more
data, and <a href="#stream_readable_push_chunk_encoding"><code>stream.push(null)</code></a> will signal the end of stream data
(<code>EOF</code>).</p>
<p>No streams in Node.js core are object mode streams. This pattern is only
used by userland streaming libraries.</p>
<p>You should set <code>objectMode</code> in your stream child class constructor on
the options object. Setting <code>objectMode</code> mid-stream is not safe.</p>
<p>For Duplex streams <code>objectMode</code> can be set exclusively for readable or
writable side with <code>readableObjectMode</code> and <code>writableObjectMode</code>
respectively. These options can be used to implement parsers and
serializers with Transform streams.</p>
<pre><code class="lang-js">const util = require('util');
const StringDecoder = require('string_decoder').StringDecoder;
const Transform = require('stream').Transform;
util.inherits(JSONParseStream, Transform);
// Gets \n-delimited JSON string data, and emits the parsed objects
function JSONParseStream() {
if (!(this instanceof JSONParseStream))
return new JSONParseStream();
Transform.call(this, { readableObjectMode : true });
this._buffer = '';
this._decoder = new StringDecoder('utf8');
}
JSONParseStream.prototype._transform = function(chunk, encoding, cb) {
this._buffer += this._decoder.write(chunk);
// split on newlines
var lines = this._buffer.split(/\r?\n/);
// keep the last partial line buffered
this._buffer = lines.pop();
for (var l = 0; l < lines.length; l++) {
var line = lines[l];
try {
var obj = JSON.parse(line);
} catch (er) {
this.emit('error', er);
return;
}
// push the parsed object out to the readable consumer
this.push(obj);
}
cb();
};
JSONParseStream.prototype._flush = function(cb) {
// Just handle any leftover
var rem = this._buffer.trim();
if (rem) {
try {
var obj = JSON.parse(rem);
} catch (er) {
this.emit('error', er);
return;
}
// push the parsed object out to the readable consumer
this.push(obj);
}
cb();
};
</code></pre>
<h3><code>stream.read(0)</code><span><a class="mark" href="#stream_stream_read_0" id="stream_stream_read_0">#</a></span></h3>
<p>There are some cases where you want to trigger a refresh of the
underlying readable stream mechanisms, without actually consuming any
data. In that case, you can call <code>stream.read(0)</code>, which will always
return null.</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="#stream_readable_read_size_1"><code>stream._read()</code></a> call.</p>
<p>There is almost never a need to do this. However, you will see some
cases in Node.js's internals where this is done, particularly in the
Readable stream class internals.</p>
<h3><code>stream.push('')</code><span><a class="mark" href="#stream_stream_push" id="stream_stream_push">#</a></span></h3>
<p>Pushing a zero-byte string or Buffer (when not in <a href="#stream_object_mode">Object mode</a>) has an
interesting side effect. Because it <em>is</em> a call to
<a href="#stream_readable_push_chunk_encoding"><code>stream.push()</code></a>, it will end the <code>reading</code> process. However, it
does <em>not</em> add any data to the readable buffer, so there's nothing for
a user to consume.</p>
<p>Very rarely, there are cases where you have no data to provide now,
but the consumer of your stream (or, perhaps, another bit of your own
code) will know when to check again, by calling <a href="#stream_readable_read_size"><code>stream.read(0)</code></a>.
In those cases, you <em>may</em> call <code>stream.push('')</code>.</p>
<p>So far, the only use case for this functionality is in the
<a href="tls.html#tls_class_cryptostream"><code>tls.CryptoStream</code></a> class, which is deprecated in Node.js/io.js v1.0. If you
find that you have to use <code>stream.push('')</code>, please consider another
approach, because it almost certainly indicates that something is
horribly wrong.</p>
<!-- [end-include:stream.md] -->
<!-- [start-include:string_decoder.md] -->
<h1>String Decoder<span><a class="mark" href="#string_decoder_string_decoder" id="string_decoder_string_decoder">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>To use this module, do <code>require('string_decoder')</code>. StringDecoder decodes a
buffer to a string. It is a simple interface to <code>buffer.toString()</code> but provides
additional support for utf8.</p>
<pre><code class="lang-js">const StringDecoder = require('string_decoder').StringDecoder;
const decoder = new StringDecoder('utf8');
const cent = new Buffer([0xC2, 0xA2]);
console.log(decoder.write(cent));
const euro = new Buffer([0xE2, 0x82, 0xAC]);
console.log(decoder.write(euro));
</code></pre>
<h2>Class: StringDecoder<span><a class="mark" href="#string_decoder_class_stringdecoder" id="string_decoder_class_stringdecoder">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div><p>Accepts a single argument, <code>encoding</code> which defaults to <code>'utf8'</code>.</p>
<h3>decoder.end()<span><a class="mark" href="#string_decoder_decoder_end" id="string_decoder_decoder_end">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.3</span>
</div><p>Returns any trailing bytes that were left in the buffer.</p>
<h3>decoder.write(buffer)<span><a class="mark" href="#string_decoder_decoder_write_buffer" id="string_decoder_decoder_write_buffer">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.1.99</span>
</div><p>Returns a decoded string.</p>
<!-- [end-include:string_decoder.md] -->
<!-- [start-include:timers.md] -->
<h1>Timers<span><a class="mark" href="#timers_timers" id="timers_timers">#</a></span></h1>
<pre class="api_stability api_stability_3">Stability: 3 - Locked</pre><p>All of the timer functions are globals. You do not need to <code>require()</code>
this module in order to use them.</p>
<h2>clearImmediate(immediateObject)<span><a class="mark" href="#timers_clearimmediate_immediateobject" id="timers_clearimmediate_immediateobject">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div><p>Stops an <code>immediateObject</code>, as created by <a href="timers.html#timers_setimmediate_callback_arg"><code>setImmediate</code></a>, from triggering.</p>
<h2>clearInterval(intervalObject)<span><a class="mark" href="#timers_clearinterval_intervalobject" id="timers_clearinterval_intervalobject">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div><p>Stops an <code>intervalObject</code>, as created by <a href="timers.html#timers_setinterval_callback_delay_arg"><code>setInterval</code></a>, from triggering.</p>
<h2>clearTimeout(timeoutObject)<span><a class="mark" href="#timers_cleartimeout_timeoutobject" id="timers_cleartimeout_timeoutobject">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div><p>Prevents a <code>timeoutObject</code>, as created by <a href="timers.html#timers_settimeout_callback_delay_arg"><code>setTimeout</code></a>, from triggering.</p>
<h2>ref()<span><a class="mark" href="#timers_ref" id="timers_ref">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div><p>If a timer was previously <code>unref()</code>d, then <code>ref()</code> can be called to explicitly
request the timer hold the program open. If the timer is already <code>ref</code>d calling
<code>ref</code> again will have no effect.</p>
<p>Returns the timer.</p>
<h2>setImmediate(callback[, arg][, ...])<span><a class="mark" href="#timers_setimmediate_callback_arg" id="timers_setimmediate_callback_arg">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div><p>Schedules "immediate" execution of <code>callback</code> after I/O events'
callbacks and before timers set by <a href="timers.html#timers_settimeout_callback_delay_arg"><code>setTimeout</code></a> and <a href="timers.html#timers_setinterval_callback_delay_arg"><code>setInterval</code></a> are
triggered. Returns an <code>immediateObject</code> for possible use with
<a href="timers.html#timers_clearimmediate_immediateobject"><code>clearImmediate</code></a>. Additional optional arguments may be passed to the
callback.</p>
<p>Callbacks for immediates are queued in the order in which they were created.
The entire callback queue is processed every event loop iteration. If an
immediate is queued from inside an executing callback, that immediate won't fire
until the next event loop iteration.</p>
<h2>setInterval(callback, delay[, arg][, ...])<span><a class="mark" href="#timers_setinterval_callback_delay_arg" id="timers_setinterval_callback_delay_arg">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div><p>Schedules repeated execution of <code>callback</code> every <code>delay</code> milliseconds.
Returns a <code>intervalObject</code> for possible use with <a href="timers.html#timers_clearinterval_intervalobject"><code>clearInterval</code></a>. Additional
optional arguments may be passed to the callback.</p>
<p>To follow browser behavior, when using delays larger than 2147483647
milliseconds (approximately 25 days) or less than 1, Node.js will use 1 as the
<code>delay</code>.</p>
<h2>setTimeout(callback, delay[, arg][, ...])<span><a class="mark" href="#timers_settimeout_callback_delay_arg" id="timers_settimeout_callback_delay_arg">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.0.1</span>
</div><p>Schedules execution of a one-time <code>callback</code> after <code>delay</code> milliseconds.
Returns a <code>timeoutObject</code> for possible use with <a href="timers.html#timers_cleartimeout_timeoutobject"><code>clearTimeout</code></a>. Additional
optional arguments may be passed to the callback.</p>
<p>The callback 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>To follow browser behavior, when using delays larger than 2147483647
milliseconds (approximately 25 days) or less than 1, the timeout is executed
immediately, as if the <code>delay</code> was set to 1.</p>
<h2>unref()<span><a class="mark" href="#timers_unref" id="timers_unref">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.9.1</span>
</div><p>The opaque value returned by <a href="timers.html#timers_settimeout_callback_delay_arg"><code>setTimeout</code></a> and <a href="timers.html#timers_setinterval_callback_delay_arg"><code>setInterval</code></a> also has the
method <code>timer.unref()</code> which allows the creation of a timer that is active but
if it is the only item left in the event loop, it won't keep the program
running. If the timer is already <code>unref</code>d calling <code>unref</code> again will have no
effect.</p>
<p>In the case of <a href="timers.html#timers_settimeout_callback_delay_arg"><code>setTimeout</code></a>, <code>unref</code> creates a separate timer that will
wakeup the event loop, creating too many of these may adversely effect event
loop performance -- use wisely.</p>
<p>Returns the timer.</p>
<!-- [end-include:timers.md] -->
<!-- [start-include:tls.md] -->
<h1>TLS (SSL)<span><a class="mark" href="#tls_tls_ssl" id="tls_tls_ssl">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>Use <code>require('tls')</code> to access this module.</p>
<p>The <code>tls</code> module uses OpenSSL to provide Transport Layer Security and/or
Secure Socket Layer: encrypted stream communication.</p>
<p>TLS/SSL is a public/private key infrastructure. Each client and each
server must have a private key. A private key is created like this:</p>
<pre><code>openssl genrsa -out ryans-key.pem 2048
</code></pre><p>All servers and some clients need to have a certificate. Certificates are public
keys signed by a Certificate Authority or self-signed. The first step to
getting a certificate is to create a "Certificate Signing Request" (CSR)
file. This is done with:</p>
<pre><code>openssl req -new -sha256 -key ryans-key.pem -out ryans-csr.pem
</code></pre><p>To create a self-signed certificate with the CSR, do this:</p>
<pre><code>openssl x509 -req -in ryans-csr.pem -signkey ryans-key.pem -out ryans-cert.pem
</code></pre><p>Alternatively you can send the CSR to a Certificate Authority for signing.</p>
<p>For Perfect Forward Secrecy, it is required to generate Diffie-Hellman
parameters:</p>
<pre><code>openssl dhparam -outform PEM -out dhparam.pem 2048
</code></pre><p>To create .pfx or .p12, do this:</p>
<pre><code>openssl pkcs12 -export -in agent5-cert.pem -inkey agent5-key.pem \
-certfile ca-cert.pem -out agent5.pfx
</code></pre><ul>
<li><code>in</code>: certificate</li>
<li><code>inkey</code>: private key</li>
<li><code>certfile</code>: all CA certs concatenated in one file like
<code>cat ca1-cert.pem ca2-cert.pem > ca-cert.pem</code></li>
</ul>
<h2>Client-initiated renegotiation attack mitigation<span><a class="mark" href="#tls_client_initiated_renegotiation_attack_mitigation" id="tls_client_initiated_renegotiation_attack_mitigation">#</a></span></h2>
<!-- type=misc -->
<p>The TLS protocol lets the client renegotiate certain aspects of the TLS session.
Unfortunately, session renegotiation requires a disproportional amount of
server-side resources, which makes it a potential vector for denial-of-service
attacks.</p>
<p>To mitigate this, renegotiations are limited to three times every 10 minutes. An
error is emitted on the <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> instance when the threshold is
exceeded. The limits are configurable:</p>
<ul>
<li><p><code>tls.CLIENT_RENEG_LIMIT</code>: renegotiation limit, default is 3.</p>
</li>
<li><p><code>tls.CLIENT_RENEG_WINDOW</code>: renegotiation window in seconds, default is
10 minutes.</p>
</li>
</ul>
<p>Don't change the defaults unless you know what you are doing.</p>
<p>To test your server, connect to it with <code>openssl s_client -connect address:port</code>
and tap <code>R<CR></code> (that's the letter <code>R</code> followed by a carriage return) a few
times.</p>
<h2>Modifying the Default TLS Cipher suite<span><a class="mark" href="#tls_modifying_the_default_tls_cipher_suite" id="tls_modifying_the_default_tls_cipher_suite">#</a></span></h2>
<p>Node.js is built with a default suite of enabled and disabled TLS ciphers.
Currently, the default cipher suite is:</p>
<pre><code>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></pre><p>This default can be overriden entirely using the <code>--tls-cipher-list</code> command
line switch. For instance, the following makes
<code>ECDHE-RSA-AES128-GCM-SHA256:!RC4</code> the default TLS cipher suite:</p>
<pre><code>node --tls-cipher-list="ECDHE-RSA-AES128-GCM-SHA256:!RC4"
</code></pre><p>Note that 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 should by used only if
absolutely necessary.</p>
<h2>ALPN, NPN and SNI<span><a class="mark" href="#tls_alpn_npn_and_sni" id="tls_alpn_npn_and_sni">#</a></span></h2>
<!-- type=misc -->
<p>ALPN (Application-Layer Protocol Negotiation Extension), NPN (Next
Protocol Negotiation) and SNI (Server Name Indication) are TLS
handshake extensions allowing you:</p>
<ul>
<li>ALPN/NPN - to use one TLS server for multiple protocols (HTTP, SPDY, HTTP/2)</li>
<li>SNI - to use one TLS server for multiple hostnames with different SSL
certificates.</li>
</ul>
<h2>Perfect Forward Secrecy<span><a class="mark" href="#tls_perfect_forward_secrecy" id="tls_perfect_forward_secrecy">#</a></span></h2>
<!-- type=misc -->
<p>The term "<a href="https://en.wikipedia.org/wiki/Perfect_forward_secrecy">Forward Secrecy</a>" or "Perfect Forward Secrecy" describes a feature of
key-agreement (i.e. key-exchange) methods. Practically it means that even if the
private key of a (your) server is compromised, communication can only be
decrypted by eavesdroppers if they manage to obtain the key-pair specifically
generated for each session.</p>
<p>This is achieved by randomly generating a key pair for key-agreement on every
handshake (in contrary to the same key for all sessions). Methods implementing
this technique, thus offering Perfect Forward Secrecy, 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/Diffie%E2%80%93Hellman_key_exchange">DHE</a> - An ephemeral version of the Diffie Hellman key-agreement protocol.</li>
<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>
</ul>
<p>Ephemeral methods may have some performance drawbacks, because key generation
is expensive.</p>
<h2>Class: CryptoStream<span><a class="mark" href="#tls_class_cryptostream" id="tls_class_cryptostream">#</a></span></h2>
<pre class="api_stability api_stability_0">Stability: 0 - Deprecated: Use <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> instead.</pre><p>This is an encrypted stream.</p>
<h3>cryptoStream.bytesWritten<span><a class="mark" href="#tls_cryptostream_byteswritten" id="tls_cryptostream_byteswritten">#</a></span></h3>
<p>A proxy to the underlying socket's bytesWritten accessor, this will return
the total bytes written to the socket, <em>including the TLS overhead</em>.</p>
<h2>Class: SecurePair<span><a class="mark" href="#tls_class_securepair" id="tls_class_securepair">#</a></span></h2>
<p>Returned by tls.createSecurePair.</p>
<h3>Event: 'secure'<span><a class="mark" href="#tls_event_secure" id="tls_event_secure">#</a></span></h3>
<p>The event is emitted from the SecurePair once the pair has successfully
established a secure connection.</p>
<p>Similarly to the checking for the server <code>'secureConnection'</code> event,
pair.cleartext.authorized should be checked to confirm whether the certificate
used properly authorized.</p>
<h2>Class: tls.Server<span><a class="mark" href="#tls_class_tls_server" id="tls_class_tls_server">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.2</span>
</div><p>This class is a subclass of <code>net.Server</code> and has the same methods on it.
Instead of accepting just raw TCP connections, this accepts encrypted
connections using TLS or SSL.</p>
<h3>Event: 'clientError'<span><a class="mark" href="#tls_event_clienterror" id="tls_event_clienterror">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.11</span>
</div><p><code>function (exception, tlsSocket) { }</code></p>
<p>When a client connection emits an <code>'error'</code> event before a secure connection is
established it will be forwarded here.</p>
<p><code>tlsSocket</code> is the <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> that the error originated from.</p>
<h3>Event: 'newSession'<span><a class="mark" href="#tls_event_newsession" id="tls_event_newsession">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.2</span>
</div><p><code>function (sessionId, sessionData, callback) { }</code></p>
<p>Emitted on creation of TLS session. May be used to store sessions in external
storage. <code>callback</code> must be invoked eventually, otherwise no data will be
sent or received from secure connection.</p>
<p>NOTE: adding this event listener will have an effect only on connections
established after addition of event listener.</p>
<h3>Event: 'OCSPRequest'<span><a class="mark" href="#tls_event_ocsprequest" id="tls_event_ocsprequest">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.13</span>
</div><p><code>function (certificate, issuer, callback) { }</code></p>
<p>Emitted when the client sends a certificate status request. You could parse
server's current certificate to obtain OCSP url and certificate id, and after
obtaining OCSP response invoke <code>callback(null, resp)</code>, where <code>resp</code> is a
<code>Buffer</code> instance. Both <code>certificate</code> and <code>issuer</code> are a <code>Buffer</code>
DER-representations of the primary and issuer's certificates. They could be used
to obtain OCSP certificate id and OCSP endpoint url.</p>
<p>Alternatively, <code>callback(null, null)</code> could be called, meaning that there is no
OCSP response.</p>
<p>Calling <code>callback(err)</code> will result in a <code>socket.destroy(err)</code> call.</p>
<p>Typical flow:</p>
<ol>
<li>Client connects to server and sends <code>'OCSPRequest'</code> to it (via status info
extension in ClientHello.)</li>
<li>Server receives request and invokes <code>'OCSPRequest'</code> event listener if present</li>
<li>Server grabs OCSP url from either <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 CA and sends it back to client via
<code>callback</code> argument</li>
<li>Client validates the response and either destroys socket or performs a
handshake.</li>
</ol>
<p>NOTE: <code>issuer</code> could be null, if the certificate is self-signed or if the issuer
is not in the root certificates list. (You could provide an issuer via <code>ca</code>
option.)</p>
<p>NOTE: adding this event listener will have an effect only on connections
established after addition of event listener.</p>
<p>NOTE: you may want to use some npm module like <a href="https://npmjs.org/package/asn1.js">asn1.js</a> to parse the
certificates.</p>
<h3>Event: 'resumeSession'<span><a class="mark" href="#tls_event_resumesession" id="tls_event_resumesession">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.9.2</span>
</div><p><code>function (sessionId, callback) { }</code></p>
<p>Emitted when client wants to resume previous TLS session. Event listener may
perform lookup in external storage using given <code>sessionId</code>, and invoke
<code>callback(null, sessionData)</code> once finished. If session can't be resumed
(i.e. doesn't exist in storage) one may call <code>callback(null, null)</code>. Calling
<code>callback(err)</code> will terminate incoming connection and destroy socket.</p>
<p>NOTE: adding this event listener will have an effect only on connections
established after addition of event listener.</p>
<p>Here's an example for using TLS session resumption:</p>
<pre><code class="lang-js">var tlsSessionStore = {};
server.on('newSession', (id, data, cb) => {
tlsSessionStore[id.toString('hex')] = data;
cb();
});
server.on('resumeSession', (id, cb) => {
cb(null, tlsSessionStore[id.toString('hex')] || null);
});
</code></pre>
<h3>Event: 'secureConnection'<span><a class="mark" href="#tls_event_secureconnection" id="tls_event_secureconnection">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.2</span>
</div><p><code>function (tlsSocket) {}</code></p>
<p>This event is emitted after a new connection has been successfully
handshaked. The argument is an instance of <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a>. It has all the
common stream methods and events.</p>
<p><code>socket.authorized</code> is a boolean value which indicates if the
client has verified by one of the supplied certificate authorities for the
server. If <code>socket.authorized</code> is false, then
<code>socket.authorizationError</code> is set to describe how authorization
failed. Implied but worth mentioning: depending on the settings of the TLS
server, you unauthorized connections may be accepted.</p>
<p><code>socket.npnProtocol</code> is a string containing the selected NPN protocol
and <code>socket.alpnProtocol</code> is a string containing the selected ALPN
protocol, When both NPN and ALPN extensions are received, ALPN takes
precedence over NPN and the next protocol is selected by ALPN. When
ALPN has no selected protocol, this returns false.</p>
<p><code>socket.servername</code> is a string containing servername requested with
SNI.</p>
<h3>server.addContext(hostname, context)<span><a class="mark" href="#tls_server_addcontext_hostname_context" id="tls_server_addcontext_hostname_context">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.3</span>
</div><p>Add secure context that will be used if client request's SNI hostname is
matching passed <code>hostname</code> (wildcards can be used). <code>context</code> can contain
<code>key</code>, <code>cert</code>, <code>ca</code> and/or any other properties from
<a href="#tls_tls_createsecurecontext_details"><code>tls.createSecureContext()</code></a> <code>options</code> argument.</p>
<h3>server.address()<span><a class="mark" href="#tls_server_address" id="tls_server_address">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.6.0</span>
</div><p>Returns the bound address, the address family name and port of the
server as reported by the operating system. See <a href="net.html#net_server_address"><code>net.Server.address()</code></a> for
more information.</p>
<h3>server.close([callback])<span><a class="mark" href="#tls_server_close_callback" id="tls_server_close_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.2</span>
</div><p>Stops the server from accepting new connections. This function is
asynchronous, the server is finally closed when the server emits a <code>'close'</code>
event. Optionally, you can pass a callback to listen for the <code>'close'</code> event.</p>
<h3>server.connections<span><a class="mark" href="#tls_server_connections" id="tls_server_connections">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.2</span>
</div><p>The number of concurrent connections on the server.</p>
<h3>server.getTicketKeys()<span><a class="mark" href="#tls_server_getticketkeys" id="tls_server_getticketkeys">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v3.0.0</span>
</div><p>Returns <code>Buffer</code> instance holding the keys currently used for
encryption/decryption of the <a href="https://www.ietf.org/rfc/rfc5077.txt">TLS Session Tickets</a></p>
<h3>server.listen(port[, hostname][, callback])<span><a class="mark" href="#tls_server_listen_port_hostname_callback" id="tls_server_listen_port_hostname_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.2</span>
</div><p>Begin accepting connections on the specified <code>port</code> and <code>hostname</code>. If the
<code>hostname</code> is omitted, the server will accept connections on any IPv6 address
(<code>::</code>) when IPv6 is available, or any IPv4 address (<code>0.0.0.0</code>) otherwise. A
port value of zero will assign a random port.</p>
<p>This function is asynchronous. The last parameter <code>callback</code> will be called
when the server has been bound.</p>
<p>See <a href="net.html#net_class_net_server"><code>net.Server</code></a> for more information.</p>
<h3>server.maxConnections<span><a class="mark" href="#tls_server_maxconnections" id="tls_server_maxconnections">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.2.0</span>
</div><p>Set this property to reject connections when the server's connection count
gets high.</p>
<h3>server.setTicketKeys(keys)<span><a class="mark" href="#tls_server_setticketkeys_keys" id="tls_server_setticketkeys_keys">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v3.0.0</span>
</div><p>Updates the keys for encryption/decryption of the <a href="https://www.ietf.org/rfc/rfc5077.txt">TLS Session Tickets</a>.</p>
<p>NOTE: the buffer should be 48 bytes long. See server <code>ticketKeys</code> option for
more information oh how it is going to be used.</p>
<p>NOTE: the change is effective only for the future server connections. Existing
or currently pending server connections will use previous keys.</p>
<h2>Class: tls.TLSSocket<span><a class="mark" href="#tls_class_tls_tlssocket" id="tls_class_tls_tlssocket">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div><p>This is a wrapped version of <a href="net.html#net_class_net_socket"><code>net.Socket</code></a> that does transparent encryption
of written data and all required TLS negotiation.</p>
<p>This instance implements a duplex <a href="stream.html#stream_stream">Stream</a> interfaces. It has all the
common stream methods and events.</p>
<p>Methods that return TLS connection meta data (e.g.
<a href="#tls_tlssocket_getpeercertificate_detailed"><code>tls.TLSSocket.getPeerCertificate()</code></a> will only return data while the
connection is open.</p>
<h2>new tls.TLSSocket(socket[, options])<span><a class="mark" href="#tls_new_tls_tlssocket_socket_options" id="tls_new_tls_tlssocket_socket_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div><p>Construct a new TLSSocket object from existing TCP socket.</p>
<p><code>socket</code> is an instance of <a href="net.html#net_class_net_socket"><code>net.Socket</code></a></p>
<p><code>options</code> is an optional object that might contain following properties:</p>
<ul>
<li><p><code>secureContext</code>: An optional TLS context object from
<a href="#tls_tls_createsecurecontext_details"><code>tls.createSecureContext()</code></a></p>
</li>
<li><p><code>isServer</code>: If <code>true</code> the TLS socket will be instantiated in server-mode.
Default: <code>false</code></p>
</li>
<li><p><code>server</code>: An optional <a href="net.html#net_class_net_server"><code>net.Server</code></a> instance</p>
</li>
<li><p><code>requestCert</code>: Optional, see <a href="#tls_tls_createsecurepair_context_isserver_requestcert_rejectunauthorized_options"><code>tls.createSecurePair()</code></a></p>
</li>
<li><p><code>rejectUnauthorized</code>: Optional, see <a href="#tls_tls_createsecurepair_context_isserver_requestcert_rejectunauthorized_options"><code>tls.createSecurePair()</code></a></p>
</li>
<li><p><code>NPNProtocols</code>: Optional, see <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></p>
</li>
<li><p><code>ALPNProtocols</code>: Optional, see [tls.createServer][]</p>
</li>
<li><p><code>SNICallback</code>: Optional, see <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a></p>
</li>
<li><p><code>session</code>: Optional, a <code>Buffer</code> instance, containing TLS session</p>
</li>
<li><p><code>requestOCSP</code>: Optional, if <code>true</code> 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</p>
</li>
</ul>
<h3>Event: 'OCSPResponse'<span><a class="mark" href="#tls_event_ocspresponse" id="tls_event_ocspresponse">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.13</span>
</div><p><code>function (response) { }</code></p>
<p>This event will be emitted if <code>requestOCSP</code> option was set. <code>response</code> is a
buffer object, containing server's OCSP response.</p>
<p>Traditionally, the <code>response</code> is a signed object from the server's CA that
contains information about server's certificate revocation status.</p>
<h3>Event: 'secureConnect'<span><a class="mark" href="#tls_event_secureconnect" id="tls_event_secureconnect">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div><p>This event is emitted after a new connection has been successfully handshaked.
The listener will be called no matter if the server's certificate was
authorized or not. It is up to the user to test <code>tlsSocket.authorized</code>
to see if the server certificate was signed by one of the specified CAs.
If <code>tlsSocket.authorized === false</code> then the error can be found in
<code>tlsSocket.authorizationError</code>. Also if ALPN or NPN was used - you can
check <code>tlsSocket.alpnProtocol</code> or <code>tlsSocket.npnProtocol</code> for the
negotiated protocol.</p>
<h3>tlsSocket.address()<span><a class="mark" href="#tls_tlssocket_address" id="tls_tlssocket_address">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div><p>Returns the bound address, the address family name and port of the
underlying socket as reported by the operating system. Returns an
object with three properties, e.g.
<code>{ port: 12346, family: 'IPv4', address: '127.0.0.1' }</code></p>
<h3>tlsSocket.authorized<span><a class="mark" href="#tls_tlssocket_authorized" id="tls_tlssocket_authorized">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div><p>A boolean that is <code>true</code> if the peer certificate was signed by one of the
specified CAs, otherwise <code>false</code></p>
<h3>tlsSocket.authorizationError<span><a class="mark" href="#tls_tlssocket_authorizationerror" id="tls_tlssocket_authorizationerror">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div><p>The reason why the peer's certificate has not been verified. This property
becomes available only when <code>tlsSocket.authorized === false</code>.</p>
<h3>tlsSocket.encrypted<span><a class="mark" href="#tls_tlssocket_encrypted" id="tls_tlssocket_encrypted">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div><p>Static boolean value, always <code>true</code>. May be used to distinguish TLS sockets
from regular ones.</p>
<h3>tlsSocket.getCipher()<span><a class="mark" href="#tls_tlssocket_getcipher" id="tls_tlssocket_getcipher">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div><p>Returns an object representing the cipher name and the SSL/TLS
protocol version of the current connection.</p>
<p>Example:
<span class="type"><name: 'AES256-SHA', version: 'TLSv1/SSLv3'></span></p>
<p>See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in
<a href="https://www.openssl.org/docs/ssl/ssl.html#DEALING-WITH-CIPHERS">https://www.openssl.org/docs/ssl/ssl.html#DEALING-WITH-CIPHERS</a> for more
information.</p>
<h3>tlsSocket.getPeerCertificate([ detailed ])<span><a class="mark" href="#tls_tlssocket_getpeercertificate_detailed" id="tls_tlssocket_getpeercertificate_detailed">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div><p>Returns an object representing the peer's certificate. The returned object has
some properties corresponding to the field of the certificate. If <code>detailed</code>
argument is <code>true</code> the full chain with <code>issuer</code> property will be returned,
if <code>false</code> only the top certificate without <code>issuer</code> property.</p>
<p>Example:</p>
<pre><code>{ subject:
{ C: 'UK',
ST: 'Acknack Ltd',
L: 'Rhys Jones',
O: 'node.js',
OU: 'Test TLS Certificate',
CN: 'localhost' },
issuerInfo:
{ C: 'UK',
ST: 'Acknack Ltd',
L: 'Rhys Jones',
O: 'node.js',
OU: 'Test TLS Certificate',
CN: 'localhost' },
issuer:
{ ... another certificate ... },
raw: < RAW DER buffer >,
valid_from: 'Nov 11 09:52:22 2009 GMT',
valid_to: 'Nov 6 09:52:22 2029 GMT',
fingerprint: '2A:7A:C2:DD:E5:F9:CC:53:72:35:99:7A:02:5A:71:38:52:EC:8A:DF',
serialNumber: 'B9B0D332A1AA5635' }
</code></pre><p>If the peer does not provide a certificate, it returns <code>null</code> or an empty
object.</p>
<h3>tlsSocket.getSession()<span><a class="mark" href="#tls_tlssocket_getsession" id="tls_tlssocket_getsession">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div><p>Return ASN.1 encoded TLS session or <code>undefined</code> if none was negotiated. Could
be used to speed up handshake establishment when reconnecting to the server.</p>
<h3>tlsSocket.getTLSTicket()<span><a class="mark" href="#tls_tlssocket_gettlsticket" id="tls_tlssocket_gettlsticket">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div><p>NOTE: Works only with client TLS sockets. Useful only for debugging, for
session reuse provide <code>session</code> option to <a href="#tls_tls_connect_options_callback"><code>tls.connect()</code></a>.</p>
<p>Return TLS session ticket or <code>undefined</code> if none was negotiated.</p>
<h3>tlsSocket.localPort<span><a class="mark" href="#tls_tlssocket_localport" id="tls_tlssocket_localport">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div><p>The numeric representation of the local port.</p>
<h3>tlsSocket.localAddress<span><a class="mark" href="#tls_tlssocket_localaddress" id="tls_tlssocket_localaddress">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div><p>The string representation of the local IP address.</p>
<h3>tlsSocket.remoteAddress<span><a class="mark" href="#tls_tlssocket_remoteaddress" id="tls_tlssocket_remoteaddress">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div><p>The string representation of the remote IP address. For example,
<code>'74.125.127.100'</code> or <code>'2001:4860:a005::68'</code>.</p>
<h3>tlsSocket.remoteFamily<span><a class="mark" href="#tls_tlssocket_remotefamily" id="tls_tlssocket_remotefamily">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div><p>The string representation of the remote IP family. <code>'IPv4'</code> or <code>'IPv6'</code>.</p>
<h3>tlsSocket.remotePort<span><a class="mark" href="#tls_tlssocket_remoteport" id="tls_tlssocket_remoteport">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div><p>The numeric representation of the remote port. For example, <code>443</code>.</p>
<h3>tlsSocket.renegotiate(options, callback)<span><a class="mark" href="#tls_tlssocket_renegotiate_options_callback" id="tls_tlssocket_renegotiate_options_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.8</span>
</div><p>Initiate TLS renegotiation process. The <code>options</code> may contain the following
fields: <code>rejectUnauthorized</code>, <code>requestCert</code> (See <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a> for
details). <code>callback(err)</code> will be executed with <code>null</code> as <code>err</code>,
once the renegotiation is successfully completed.</p>
<p>NOTE: Can be used to request peer's certificate after the secure connection
has been established.</p>
<p>ANOTHER NOTE: When running as the server, socket will be destroyed
with an error after <code>handshakeTimeout</code> timeout.</p>
<h3>tlsSocket.setMaxSendFragment(size)<span><a class="mark" href="#tls_tlssocket_setmaxsendfragment_size" id="tls_tlssocket_setmaxsendfragment_size">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.11</span>
</div><p>Set maximum TLS fragment size (default and maximum value is: <code>16384</code>, minimum
is: <code>512</code>). Returns <code>true</code> on success, <code>false</code> otherwise.</p>
<p>Smaller fragment size decreases buffering latency on the client: large
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>
<h2>tls.connect(options[, callback])<span><a class="mark" href="#tls_tls_connect_options_callback" id="tls_tls_connect_options_callback">#</a></span></h2>
<h2>tls.connect(port[, host][, options][, callback])<span><a class="mark" href="#tls_tls_connect_port_host_options_callback" id="tls_tls_connect_port_host_options_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.3</span>
</div><p>Creates a new client connection to the given <code>port</code> and <code>host</code> (old API) or
<code>options.port</code> and <code>options.host</code>. (If <code>host</code> is omitted, it defaults to
<code>localhost</code>.) <code>options</code> should be an object which specifies:</p>
<ul>
<li><p><code>host</code>: Host the client should connect to</p>
</li>
<li><p><code>port</code>: Port the client should connect to</p>
</li>
<li><p><code>socket</code>: Establish secure connection on a given socket rather than
creating a new socket. If this option is specified, <code>host</code> and <code>port</code>
are ignored.</p>
</li>
<li><p><code>path</code>: Creates unix socket connection to path. If this option is
specified, <code>host</code> and <code>port</code> are ignored.</p>
</li>
<li><p><code>pfx</code>: A string or <code>Buffer</code> containing the private key, certificate and
CA certs of the client in PFX or PKCS12 format.</p>
</li>
<li><p><code>key</code>: A string or <code>Buffer</code> containing the private key of the client in
PEM format. (Could be an array of keys).</p>
</li>
<li><p><code>passphrase</code>: A string of passphrase for the private key or pfx.</p>
</li>
<li><p><code>cert</code>: A string or <code>Buffer</code> containing the certificate key of the client in
PEM format. (Could be an array of certs).</p>
</li>
<li><p><code>ca</code>: A string, <code>Buffer</code> or array of strings or <code>Buffer</code>s of trusted
certificates in PEM format. If this is omitted several well known "root"
CAs will be used, like VeriSign. These are used to authorize connections.</p>
</li>
<li><p><code>ciphers</code>: A string describing the ciphers to use or exclude, separated by
<code>:</code>. Uses the same default cipher suite as <a href="#tls_tls_createserver_options_secureconnectionlistener"><code>tls.createServer()</code></a>.</p>
</li>
<li><p><code>rejectUnauthorized</code>: If <code>true</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. Default: <code>true</code>.</p>
</li>
<li><p><code>NPNProtocols</code>: An array of strings or <code>Buffer</code>s containing supported NPN
protocols. <code>Buffer</code>s should have following format: <code>0x05hello0x05world</code>,
where first byte is next protocol name's length. (Passing array should
usually be much simpler: <code>['hello', 'world']</code>.)</p>
</li>
<li><p><code>ALPNProtocols</code>: An array of strings or <code>Buffer</code>s containing
supported ALPN protocols. <code>Buffer</code>s should have following format:
<code>0x05hello0x05world</code>, where the first byte is the next protocol
name's length. (Passing array should usually be much simpler:
<code>['hello', 'world']</code>.)</p>
</li>
<li><p><code>servername</code>: Servername for SNI (Server Name Indication) TLS extension.</p>
</li>
<li><p><code>checkServerIdentity(servername, cert)</code>: Provide an override for checking
server's hostname against the certificate. Should return an error if verification
fails. Return <code>undefined</code> if passing.</p>
</li>
<li><p><code>secureProtocol</code>: The SSL method to use, e.g. <code>SSLv3_method</code> to force
SSL version 3. The possible values depend on your installation of
OpenSSL and are defined in the constant <a href="https://www.openssl.org/docs/ssl/ssl.html#DEALING-WITH-PROTOCOL-METHODS">SSL_METHODS</a>.</p>
</li>
<li><p><code>secureContext</code>: An optional TLS context object from
<code>tls.createSecureContext( ... )</code>. Could it be used for caching client
certificates, key, and CA certificates.</p>
</li>
<li><p><code>session</code>: A <code>Buffer</code> instance, containing TLS session.</p>
</li>
</ul>
<p>The <code>callback</code> parameter will be added as a listener for the
<a href="#tls_event_secureconnect"><code>'secureConnect'</code></a> event.</p>
<p><code>tls.connect()</code> returns a <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a> object.</p>
<p>Here is an example of a client of echo server as described previously:</p>
<pre><code class="lang-js">const tls = require('tls');
const fs = require('fs');
const options = {
// These are necessary only if using the client certificate authentication
key: fs.readFileSync('client-key.pem'),
cert: fs.readFileSync('client-cert.pem'),
// This is necessary only if the server uses the self-signed certificate
ca: [ fs.readFileSync('server-cert.pem') ]
};
var socket = tls.connect(8000, options, () => {
console.log('client connected',
socket.authorized ? 'authorized' : 'unauthorized');
process.stdin.pipe(socket);
process.stdin.resume();
});
socket.setEncoding('utf8');
socket.on('data', (data) => {
console.log(data);
});
socket.on('end', () => {
server.close();
});
</code></pre>
<p>Or</p>
<pre><code class="lang-js">const tls = require('tls');
const fs = require('fs');
const options = {
pfx: fs.readFileSync('client.pfx')
};
var socket = tls.connect(8000, options, () => {
console.log('client connected',
socket.authorized ? 'authorized' : 'unauthorized');
process.stdin.pipe(socket);
process.stdin.resume();
});
socket.setEncoding('utf8');
socket.on('data', (data) => {
console.log(data);
});
socket.on('end', () => {
server.close();
});
</code></pre>
<h2>tls.createSecureContext(details)<span><a class="mark" href="#tls_tls_createsecurecontext_details" id="tls_tls_createsecurecontext_details">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.13</span>
</div><p>Creates a credentials object, with the optional details being a
dictionary with keys:</p>
<ul>
<li><code>pfx</code> : A string or buffer holding the PFX or PKCS12 encoded private
key, certificate and CA certificates</li>
<li><code>key</code>: A string or <code>Buffer</code> containing the private key of the server in
PEM format. To support multiple keys using different algorithms, an array
can be provided. It can either be a plain array of keys, or an array of
objects in the format <code>{pem: key, passphrase: passphrase}</code>. (Required)</li>
<li><code>passphrase</code> : A string of passphrase for the private key or pfx</li>
<li><code>cert</code> : A string holding the PEM encoded certificate</li>
<li><code>ca</code>: A string, <code>Buffer</code> or array of strings or <code>Buffer</code>s of trusted
certificates in PEM format. If this is omitted several well known "root"
CAs will be used, like VeriSign. These are used to authorize connections.</li>
<li><code>crl</code> : Either a string or list of strings of PEM encoded CRLs
(Certificate Revocation List)</li>
<li><code>ciphers</code>: A string describing the ciphers to use or exclude.
Consult
<a href="https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT">https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT</a>
for details on the format.</li>
<li><code>honorCipherOrder</code> : When choosing a cipher, use the server's preferences
instead of the client preferences. For further details see <code>tls</code> module
documentation.</li>
</ul>
<p>If no 'ca' details are given, then Node.js will use the default
publicly trusted list of CAs as given in
<a href="http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt">http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt</a>.</p>
<h2>tls.createSecurePair([context][, isServer][, requestCert][, rejectUnauthorized][, options])<span><a class="mark" href="#tls_tls_createsecurepair_context_isserver_requestcert_rejectunauthorized_options" id="tls_tls_createsecurepair_context_isserver_requestcert_rejectunauthorized_options">#</a></span></h2>
<p>Creates a new secure pair object with two streams, one of which reads/writes
encrypted data, and one reads/writes cleartext data.
Generally the encrypted one is piped to/from an incoming encrypted data stream,
and the cleartext one is used as a replacement for the initial encrypted stream.</p>
<ul>
<li><p><code>credentials</code>: A secure context object from tls.createSecureContext( ... )</p>
</li>
<li><p><code>isServer</code>: A boolean indicating whether this tls connection should be
opened as a server or a client.</p>
</li>
<li><p><code>requestCert</code>: A boolean indicating whether a server should request a
certificate from a connecting client. Only applies to server connections.</p>
</li>
<li><p><code>rejectUnauthorized</code>: A boolean indicating whether a server should
automatically reject clients with invalid certificates. Only applies to
servers with <code>requestCert</code> enabled.</p>
</li>
<li><p><code>options</code>: An object with common SSL options. See <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a>.</p>
</li>
</ul>
<p><code>tls.createSecurePair()</code> returns a SecurePair object with <code>cleartext</code> and
<code>encrypted</code> stream properties.</p>
<p>NOTE: <code>cleartext</code> has the same APIs as <a href="#tls_class_tls_tlssocket"><code>tls.TLSSocket</code></a></p>
<h2>tls.createServer(options[, secureConnectionListener])<span><a class="mark" href="#tls_tls_createserver_options_secureconnectionlistener" id="tls_tls_createserver_options_secureconnectionlistener">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.2</span>
</div><p>Creates a new <a href="#tls_class_tls_server">tls.Server</a>. The <code>connectionListener</code> argument is
automatically set as a listener for the <a href="#tls_event_secureconnection"><code>'secureConnection'</code></a> event. The
<code>options</code> object has these possibilities:</p>
<ul>
<li><p><code>pfx</code>: A string or <code>Buffer</code> containing the private key, certificate and
CA certs of the server in PFX or PKCS12 format. (Mutually exclusive with
the <code>key</code>, <code>cert</code> and <code>ca</code> options.)</p>
</li>
<li><p><code>key</code>: A string or <code>Buffer</code> containing the private key of the server in
PEM format. To support multiple keys using different algorithms, an array
can be provided. It can either be a plain array of keys, or an array of
objects in the format <code>{pem: key, passphrase: passphrase}</code>. (Required)</p>
</li>
<li><p><code>passphrase</code>: A string of passphrase for the private key or pfx.</p>
</li>
<li><p><code>cert</code>: A string or <code>Buffer</code> containing the certificate key of the server in
PEM format. (Could be an array of certs). (Required)</p>
</li>
<li><p><code>ca</code>: A string, <code>Buffer</code> or array of strings or <code>Buffer</code>s of trusted
certificates in PEM format. If this is omitted several well known "root"
CAs will be used, like VeriSign. These are used to authorize connections.</p>
</li>
<li><p><code>crl</code> : Either a string or list of strings of PEM encoded CRLs (Certificate
Revocation List)</p>
</li>
<li><p><code>ciphers</code>: A string describing the ciphers to use or exclude, separated by
<code>:</code>. The default cipher suite is:</p>
<pre><code class="lang-js">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></pre>
<p>The default cipher suite prefers GCM ciphers for <a href="https://www.chromium.org/Home/chromium-security/education/tls#TOC-Deprecation-of-TLS-Features-Algorithms-in-Chrome">Chrome's 'modern
cryptography' setting</a> and also prefers ECDHE and DHE ciphers for Perfect
Forward secrecy, while offering <em>some</em> backward compatibiltity.</p>
<p>128 bit AES is preferred over 192 and 256 bit AES in light of <a href="https://www.schneier.com/blog/archives/2009/07/another_new_aes.html">specific
attacks affecting larger AES key sizes</a>.</p>
<p>Old clients that rely on insecure and deprecated RC4 or DES-based ciphers
(like Internet Explorer 6) aren't able to complete the handshake with the default
configuration. If you absolutely must support these clients, 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 <a href="https://www.openssl.org/docs/apps/ciphers.html#CIPHER-LIST-FORMAT">OpenSSL cipher list format documentation</a>.</p>
</li>
<li><p><code>ecdhCurve</code>: A string describing a named curve to use for ECDH key agreement
or false to disable ECDH.</p>
<p>Defaults to <code>prime256v1</code> (NIST P-256). Use <a href="crypto.html#crypto_crypto_getcurves"><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.</p>
</li>
<li><p><code>dhparam</code>: A string or <code>Buffer</code> containing Diffie Hellman parameters,
required for Perfect Forward Secrecy. Use <code>openssl dhparam</code> to create it.
Its key length should be greater than or equal to 1024 bits, otherwise
it throws an error. It is strongly recommended to use 2048 bits or
more for stronger security. If omitted or invalid, it is silently
discarded and DHE ciphers won't be available.</p>
</li>
<li><p><code>handshakeTimeout</code>: Abort the connection if the SSL/TLS handshake does not
finish in this many milliseconds. The default is 120 seconds.</p>
<p>A <code>'clientError'</code> is emitted on the <code>tls.Server</code> object whenever a handshake
times out.</p>
</li>
<li><p><code>honorCipherOrder</code> : When choosing a cipher, use the server's preferences
instead of the client preferences. Default: <code>true</code>.</p>
</li>
<li><p><code>requestCert</code>: If <code>true</code> the server will request a certificate from
clients that connect and attempt to verify that certificate. Default:
<code>false</code>.</p>
</li>
<li><p><code>rejectUnauthorized</code>: If <code>true</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>. Default: <code>false</code>.</p>
</li>
<li><p><code>NPNProtocols</code>: An array or <code>Buffer</code> of possible NPN protocols. (Protocols
should be ordered by their priority).</p>
</li>
<li><p><code>ALPNProtocols</code>: An array or <code>Buffer</code> of possible ALPN
protocols. (Protocols should be ordered by their priority). When
the server receives both NPN and ALPN extensions from the client,
ALPN takes precedence over NPN and the server does not send an NPN
extension to the client.</p>
</li>
<li><p><code>SNICallback(servername, cb)</code>: A function that will be called if client
supports SNI TLS extension. Two argument will be passed to it: <code>servername</code>,
and <code>cb</code>. <code>SNICallback</code> should invoke <code>cb(null, ctx)</code>, where <code>ctx</code> is a
SecureContext instance.
(You can use <code>tls.createSecureContext(...)</code> to get proper
SecureContext). If <code>SNICallback</code> wasn't provided the default callback with
high-level API will be used (see below).</p>
</li>
<li><p><code>sessionTimeout</code>: An integer specifying the seconds after which TLS
session identifiers and TLS session tickets created by the server are
timed out. See <a href="https://www.openssl.org/docs/ssl/SSL_CTX_set_timeout.html">SSL_CTX_set_timeout</a> for more details.</p>
</li>
<li><p><code>ticketKeys</code>: A 48-byte <code>Buffer</code> instance consisting of 16-byte prefix,
16-byte hmac key, 16-byte AES key. You could use it to accept tls session
tickets on multiple instances of tls server.</p>
<p>NOTE: Automatically shared between <code>cluster</code> module workers.</p>
</li>
<li><p><code>sessionIdContext</code>: A string containing an opaque identifier for session
resumption. If <code>requestCert</code> is <code>true</code>, the default is MD5 hash value
generated from command-line. (In FIPS mode a truncated SHA1 hash is
used instead.) Otherwise, the default is not provided.</p>
</li>
<li><p><code>secureProtocol</code>: The SSL method to use, e.g. <code>SSLv3_method</code> to force
SSL version 3. The possible values depend on your installation of
OpenSSL and are defined in the constant <a href="https://www.openssl.org/docs/ssl/ssl.html#DEALING-WITH-PROTOCOL-METHODS">SSL_METHODS</a>.</p>
</li>
</ul>
<p>Here is a simple example echo server:</p>
<pre><code class="lang-js">const tls = require('tls');
const fs = require('fs');
const options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem'),
// This is necessary only if using the client certificate authentication.
requestCert: true,
// This is necessary only if the client uses the self-signed certificate.
ca: [ fs.readFileSync('client-cert.pem') ]
};
var server = tls.createServer(options, (socket) => {
console.log('server connected',
socket.authorized ? 'authorized' : 'unauthorized');
socket.write('welcome!\n');
socket.setEncoding('utf8');
socket.pipe(socket);
});
server.listen(8000, () => {
console.log('server bound');
});
</code></pre>
<p>Or</p>
<pre><code class="lang-js">const tls = require('tls');
const fs = require('fs');
const options = {
pfx: fs.readFileSync('server.pfx'),
// This is necessary only if using the client certificate authentication.
requestCert: true,
};
var server = tls.createServer(options, (socket) => {
console.log('server connected',
socket.authorized ? 'authorized' : 'unauthorized');
socket.write('welcome!\n');
socket.setEncoding('utf8');
socket.pipe(socket);
});
server.listen(8000, () => {
console.log('server bound');
});
</code></pre>
<p>You can test this server by connecting to it with <code>openssl s_client</code>:</p>
<pre><code>openssl s_client -connect 127.0.0.1:8000
</code></pre><h2>tls.getCiphers()<span><a class="mark" href="#tls_tls_getciphers" id="tls_tls_getciphers">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.10.2</span>
</div><p>Returns an array with the names of the supported SSL ciphers.</p>
<p>Example:</p>
<pre><code class="lang-js">var ciphers = tls.getCiphers();
console.log(ciphers); // ['AES128-SHA', 'AES256-SHA', ...]
</code></pre>
<!-- [end-include:tls.md] -->
<!-- [start-include:tty.md] -->
<h1>TTY<span><a class="mark" href="#tty_tty" id="tty_tty">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>The <code>tty</code> module houses the <code>tty.ReadStream</code> and <code>tty.WriteStream</code> classes. In
most cases, you will not need to use this module directly.</p>
<p>When Node.js detects that it is being run inside a TTY context, then <code>process.stdin</code>
will be a <code>tty.ReadStream</code> instance and <code>process.stdout</code> will be
a <code>tty.WriteStream</code> instance. The preferred way to check if Node.js is being run
in a TTY context is to check <code>process.stdout.isTTY</code>:</p>
<pre><code>$ node -p -e "Boolean(process.stdout.isTTY)"
true
$ node -p -e "Boolean(process.stdout.isTTY)" | cat
false
</code></pre><h2>Class: ReadStream<span><a class="mark" href="#tty_class_readstream" id="tty_class_readstream">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><p>A <code>net.Socket</code> subclass that represents the readable portion of a tty. In normal
circumstances, <code>process.stdin</code> will be the only <code>tty.ReadStream</code> instance in any
Node.js program (only when <code>isatty(0)</code> is true).</p>
<h3>rs.isRaw<span><a class="mark" href="#tty_rs_israw" id="tty_rs_israw">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div><p>A <code>Boolean</code> that is initialized to <code>false</code>. It represents the current "raw" state
of the <code>tty.ReadStream</code> instance.</p>
<h3>rs.setRawMode(mode)<span><a class="mark" href="#tty_rs_setrawmode_mode" id="tty_rs_setrawmode_mode">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div><p><code>mode</code> should be <code>true</code> or <code>false</code>. This sets the properties of the
<code>tty.ReadStream</code> to act either as a raw device or default. <code>isRaw</code> will be set
to the resulting mode.</p>
<h2>Class: WriteStream<span><a class="mark" href="#tty_class_writestream" id="tty_class_writestream">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><p>A <code>net.Socket</code> subclass that represents the writable portion of a tty. In normal
circumstances, <code>process.stdout</code> will be the only <code>tty.WriteStream</code> instance
ever created (and only when <code>isatty(1)</code> is true).</p>
<h3>Event: 'resize'<span><a class="mark" href="#tty_event_resize" id="tty_event_resize">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div><p><code>function () {}</code></p>
<p>Emitted by <code>refreshSize()</code> when either of the <code>columns</code> or <code>rows</code> properties
has changed.</p>
<pre><code class="lang-js">process.stdout.on('resize', () => {
console.log('screen size has changed!');
console.log(`${process.stdout.columns}x${process.stdout.rows}`);
});
</code></pre>
<h3>ws.columns<span><a class="mark" href="#tty_ws_columns" id="tty_ws_columns">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div><p>A <code>Number</code> that gives the number of columns the TTY currently has. This property
gets updated on <code>'resize'</code> events.</p>
<h3>ws.rows<span><a class="mark" href="#tty_ws_rows" id="tty_ws_rows">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.7.7</span>
</div><p>A <code>Number</code> that gives the number of rows the TTY currently has. This property
gets updated on <code>'resize'</code> events.</p>
<h2>tty.isatty(fd)<span><a class="mark" href="#tty_tty_isatty_fd" id="tty_tty_isatty_fd">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><p>Returns <code>true</code> or <code>false</code> depending on if the <code>fd</code> is associated with a
terminal.</p>
<h2>tty.setRawMode(mode)<span><a class="mark" href="#tty_tty_setrawmode_mode" id="tty_tty_setrawmode_mode">#</a></span></h2>
<pre class="api_stability api_stability_0">Stability: 0 - Deprecated: Use <a href="#tty_rs_setrawmode_mode">tty.ReadStream#setRawMode</a> (i.e. process.stdin.setRawMode) instead.</pre><!-- [end-include:tty.md] -->
<!-- [start-include:url.md] -->
<h1>URL<span><a class="mark" href="#url_url" id="url_url">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>This module has utilities for URL resolution and parsing.
Call <code>require('url')</code> to use it.</p>
<h2>URL Parsing<span><a class="mark" href="#url_url_parsing" id="url_url_parsing">#</a></span></h2>
<p>Parsed URL objects have some or all of the following fields, depending on
whether or not they exist in the URL string. Any parts that are not in the URL
string will not be in the parsed object. Examples are shown for the URL</p>
<p><code>'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'</code></p>
<ul>
<li><p><code>href</code>: The full URL that was originally parsed. Both the protocol and host are lowercased.</p>
<p> Example: <code>'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'</code></p>
</li>
<li><p><code>protocol</code>: The request protocol, lowercased.</p>
<p> Example: <code>'http:'</code></p>
</li>
<li><p><code>slashes</code>: The protocol requires slashes after the colon.</p>
<p> Example: true or false</p>
</li>
<li><p><code>host</code>: The full lowercased host portion of the URL, including port
information.</p>
<p> Example: <code>'host.com:8080'</code></p>
</li>
<li><p><code>auth</code>: The authentication information portion of a URL.</p>
<p> Example: <code>'user:pass'</code></p>
</li>
<li><p><code>hostname</code>: Just the lowercased hostname portion of the host.</p>
<p> Example: <code>'host.com'</code></p>
</li>
<li><p><code>port</code>: The port number portion of the host.</p>
<p> Example: <code>'8080'</code></p>
</li>
<li><p><code>pathname</code>: The path section of the URL, that comes after the host and
before the query, including the initial slash if present. No decoding is
performed.</p>
<p> Example: <code>'/p/a/t/h'</code></p>
</li>
<li><p><code>search</code>: The 'query string' portion of the URL, including the leading
question mark.</p>
<p> Example: <code>'?query=string'</code></p>
</li>
<li><p><code>path</code>: Concatenation of <code>pathname</code> and <code>search</code>. No decoding is performed.</p>
<p> Example: <code>'/p/a/t/h?query=string'</code></p>
</li>
<li><p><code>query</code>: Either the 'params' portion of the query string, or a
querystring-parsed object.</p>
<p> Example: <code>'query=string'</code> or <code>{'query':'string'}</code></p>
</li>
<li><p><code>hash</code>: The 'fragment' portion of the URL including the pound-sign.</p>
<p> Example: <code>'#hash'</code></p>
</li>
</ul>
<h3>Escaped Characters<span><a class="mark" href="#url_escaped_characters" id="url_escaped_characters">#</a></span></h3>
<p>Spaces (<code>' '</code>) and the following characters will be automatically escaped in the
properties of URL objects:</p>
<pre><code>< > " ` \r \n \t { } | \ ^ '
</code></pre><hr>
<p>The following methods are provided by the URL module:</p>
<h2>url.format(urlObj)<span><a class="mark" href="#url_url_format_urlobj" id="url_url_format_urlobj">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.25</span>
</div><p>Take a parsed URL object, and return a formatted URL string.</p>
<p>Here's how the formatting process works:</p>
<ul>
<li><code>href</code> will be ignored.</li>
<li><code>path</code> will be ignored.</li>
<li><code>protocol</code> is treated the same with or without the trailing <code>:</code> (colon).<ul>
<li>The protocols <code>http</code>, <code>https</code>, <code>ftp</code>, <code>gopher</code>, <code>file</code> will be
postfixed with <code>://</code> (colon-slash-slash) as long as <code>host</code>/<code>hostname</code> are present.</li>
<li>All other protocols <code>mailto</code>, <code>xmpp</code>, <code>aim</code>, <code>sftp</code>, <code>foo</code>, etc will
be postfixed with <code>:</code> (colon).</li>
</ul>
</li>
<li><code>slashes</code> set to <code>true</code> if the protocol requires <code>://</code> (colon-slash-slash)<ul>
<li>Only needs to be set for protocols not previously listed as requiring
slashes, such as <code>mongodb://localhost:8000/</code>, or if <code>host</code>/<code>hostname</code> are absent.</li>
</ul>
</li>
<li><code>auth</code> will be used if present.</li>
<li><code>hostname</code> will only be used if <code>host</code> is absent.</li>
<li><code>port</code> will only be used if <code>host</code> is absent.</li>
<li><code>host</code> will be used in place of <code>hostname</code> and <code>port</code>.</li>
<li><code>pathname</code> is treated the same with or without the leading <code>/</code> (slash).</li>
<li><code>query</code> (object; see <code>querystring</code>) will only be used if <code>search</code> is absent.</li>
<li><code>search</code> will be used in place of <code>query</code>.<ul>
<li>It is treated the same with or without the leading <code>?</code> (question mark).</li>
</ul>
</li>
<li><code>hash</code> is treated the same with or without the leading <code>#</code> (pound sign, anchor).</li>
</ul>
<h2>url.parse(urlStr[, parseQueryString][, slashesDenoteHost])<span><a class="mark" href="#url_url_parse_urlstr_parsequerystring_slashesdenotehost" id="url_url_parse_urlstr_parsequerystring_slashesdenotehost">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.25</span>
</div><p>Take a URL string, and return an object.</p>
<p>Pass <code>true</code> as the second argument to also parse the query string using the
<code>querystring</code> module. If <code>true</code> then the <code>query</code> property will always be
assigned an object, and the <code>search</code> property will always be a (possibly
empty) string. If <code>false</code> then the <code>query</code> property will not be parsed or
decoded. Defaults to <code>false</code>.</p>
<p>Pass <code>true</code> as the third argument to treat <code>//foo/bar</code> as
<code>{ host: 'foo', pathname: '/bar' }</code> rather than
<code>{ pathname: '//foo/bar' }</code>. Defaults to <code>false</code>.</p>
<h2>url.resolve(from, to)<span><a class="mark" href="#url_url_resolve_from_to" id="url_url_resolve_from_to">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.1.25</span>
</div><p>Take a base URL, and a href URL, and resolve them as a browser would for
an anchor tag. Examples:</p>
<pre><code class="lang-js">url.resolve('/one/two/three', 'four') // '/one/two/four'
url.resolve('http://example.com/', '/one') // 'http://example.com/one'
url.resolve('http://example.com/one', '/two') // 'http://example.com/two'
</code></pre>
<!-- [end-include:url.md] -->
<!-- [start-include:util.md] -->
<h1>Util<span><a class="mark" href="#util_util" id="util_util">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>These functions are in the module <code>'util'</code>. Use <code>require('util')</code> to
access them.</p>
<p>The <code>util</code> module is primarily designed to support the needs of Node.js's
internal APIs. Many of these utilities are useful for your own
programs. If you find that these functions are lacking for your
purposes, however, you are encouraged to write your own utilities. We
are not interested in any future additions to the <code>util</code> module that
are unnecessary for Node.js's internal functionality.</p>
<h2>util.debug(string)<span><a class="mark" href="#util_util_debug_string" id="util_util_debug_string">#</a></span></h2>
<pre class="api_stability api_stability_0">Stability: 0 - Deprecated: Use <a href="console.html#console_console_error_data"><code>console.error()</code></a> instead.</pre><p>Deprecated predecessor of <code>console.error</code>.</p>
<h2>util.debuglog(section)<span><a class="mark" href="#util_util_debuglog_section" id="util_util_debuglog_section">#</a></span></h2>
<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> The section of the program to be debugged</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>This is used to create a function which conditionally writes to stderr
based on the existence of a <code>NODE_DEBUG</code> environment variable. If the
<code>section</code> name appears in that environment variable, then the returned
function will be similar to <code>console.error()</code>. If not, then the
returned function is a no-op.</p>
<p>For example:</p>
<pre><code class="lang-js">var debuglog = util.debuglog('foo');
var bar = 123;
debuglog('hello from foo [%d]', bar);
</code></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>FOO 3245: hello from foo [123]
</code></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>You may separate multiple <code>NODE_DEBUG</code> environment variables with a
comma. For example, <code>NODE_DEBUG=fs,net,tls</code>.</p>
<h2>util.deprecate(function, string)<span><a class="mark" href="#util_util_deprecate_function_string" id="util_util_deprecate_function_string">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.8.0</span>
</div><p>Marks that a method should not be used any more.</p>
<pre><code class="lang-js">const util = require('util');
exports.puts = util.deprecate(function() {
for (var i = 0, len = arguments.length; i < len; ++i) {
process.stdout.write(arguments[i] + '\n');
}
}, 'util.puts: Use console.log instead');
</code></pre>
<p>It returns a modified function which warns once by default.</p>
<p>If <code>--no-deprecation</code> is set then this function is a NO-OP. Configurable
at run-time through the <code>process.noDeprecation</code> boolean (only effective
when set before a module is loaded.)</p>
<p>If <code>--trace-deprecation</code> is set, a warning and a stack trace are logged
to the console the first time the deprecated API is used. Configurable
at run-time through the <code>process.traceDeprecation</code> boolean.</p>
<p>If <code>--throw-deprecation</code> is set then the application throws an exception
when the deprecated API is used. Configurable at run-time through the
<code>process.throwDeprecation</code> boolean.</p>
<p><code>process.throwDeprecation</code> takes precedence over <code>process.traceDeprecation</code>.</p>
<h2>util.error([...])<span><a class="mark" href="#util_util_error" id="util_util_error">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
<span>Deprecated since: v0.11.3 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated: Use <a href="console.html#console_console_error_data"><code>console.error()</code></a> instead.</pre><p>Deprecated predecessor of <code>console.error</code>.</p>
<h2>util.format(format[, ...])<span><a class="mark" href="#util_util_format_format" id="util_util_format_format">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.3</span>
</div><p>Returns a formatted string using the first argument as a <code>printf</code>-like format.</p>
<p>The first argument is a string that contains zero or more <em>placeholders</em>.
Each placeholder is replaced with the converted value from its corresponding
argument. Supported placeholders are:</p>
<ul>
<li><code>%s</code> - String.</li>
<li><code>%d</code> - Number (both integer and float).</li>
<li><code>%j</code> - JSON. Replaced with the string <code>'[Circular]'</code> if the argument
contains circular references.</li>
<li><code>%%</code> - single percent sign (<code>'%'</code>). This does not consume an argument.</li>
</ul>
<p>If the placeholder does not have a corresponding argument, the placeholder is
not replaced.</p>
<pre><code class="lang-js">util.format('%s:%s', 'foo'); // 'foo:%s'
</code></pre>
<p>If there are more arguments than placeholders, the extra arguments are
coerced to strings (for objects and symbols, <code>util.inspect()</code> is used)
and then concatenated, delimited by a space.</p>
<pre><code class="lang-js">util.format('%s:%s', 'foo', 'bar', 'baz'); // 'foo:bar baz'
</code></pre>
<p>If the first argument is not a format string then <code>util.format()</code> returns
a string that is the concatenation of all its arguments separated by spaces.
Each argument is converted to a string with <code>util.inspect()</code>.</p>
<pre><code class="lang-js">util.format(1, 2, 3); // '1 2 3'
</code></pre>
<h2>util.inherits(constructor, superConstructor)<span><a class="mark" href="#util_util_inherits_constructor_superconstructor" id="util_util_inherits_constructor_superconstructor">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div><p>Inherit the prototype methods from one <a href="https://developer.mozilla.org/en/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>As an additional convenience, <code>superConstructor</code> will be accessible
through the <code>constructor.super_</code> property.</p>
<pre><code class="lang-js">const util = require('util');
const EventEmitter = require('events');
function MyStream() {
EventEmitter.call(this);
}
util.inherits(MyStream, EventEmitter);
MyStream.prototype.write = function(data) {
this.emit('data', data);
}
var stream = new MyStream();
console.log(stream instanceof EventEmitter); // true
console.log(MyStream.super_ === EventEmitter); // true
stream.on('data', (data) => {
console.log(`Received data: "${data}"`);
})
stream.write('It works!'); // Received data: "It works!"
</code></pre>
<h2>util.inspect(object[, options])<span><a class="mark" href="#util_util_inspect_object_options" id="util_util_inspect_object_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
</div><p>Return a string representation of <code>object</code>, which is useful for debugging.</p>
<p>An optional <em>options</em> object may be passed that alters certain aspects of the
formatted string:</p>
<ul>
<li><p><code>showHidden</code> - if <code>true</code> then the object's non-enumerable and symbol
properties will be shown too. Defaults to <code>false</code>.</p>
</li>
<li><p><code>depth</code> - tells <code>inspect</code> how many times to recurse while formatting the
object. This is useful for inspecting large complicated objects. Defaults to
<code>2</code>. To make it recurse indefinitely pass <code>null</code>.</p>
</li>
<li><p><code>colors</code> - if <code>true</code>, then the output will be styled with ANSI color codes.
Defaults to <code>false</code>. Colors are customizable, see <a href="#util_customizing_util_inspect_colors">Customizing
<code>util.inspect</code> colors</a>.</p>
</li>
<li><p><code>customInspect</code> - if <code>false</code>, then custom <code>inspect(depth, opts)</code> functions
defined on the objects being inspected won't be called. Defaults to <code>true</code>.</p>
</li>
</ul>
<p>Example of inspecting all properties of the <code>util</code> object:</p>
<pre><code class="lang-js">const util = require('util');
console.log(util.inspect(util, { showHidden: true, depth: null }));
</code></pre>
<p>Values may supply their own custom <code>inspect(depth, opts)</code> functions, when
called they receive the current depth in the recursive inspection, as well as
the options object passed to <code>util.inspect()</code>.</p>
<h3>Customizing <code>util.inspect</code> colors<span><a class="mark" href="#util_customizing_util_inspect_colors" id="util_customizing_util_inspect_colors">#</a></span></h3>
<!-- type=misc -->
<p>Color output (if enabled) of <code>util.inspect</code> is customizable globally
via <code>util.inspect.styles</code> and <code>util.inspect.colors</code> objects.</p>
<p><code>util.inspect.styles</code> is a map assigning each style a color
from <code>util.inspect.colors</code>.
Highlighted styles and their default values are:</p>
<ul>
<li><code>number</code> (yellow)</li>
<li><code>boolean</code> (yellow)</li>
<li><code>string</code> (green)</li>
<li><code>date</code> (magenta)</li>
<li><code>regexp</code> (red)</li>
<li><code>null</code> (bold)</li>
<li><code>undefined</code> (grey)</li>
<li><code>special</code> - only function at this time (cyan)</li>
<li><code>name</code> (intentionally no styling)</li>
</ul>
<p>Predefined color codes are: <code>white</code>, <code>grey</code>, <code>black</code>, <code>blue</code>, <code>cyan</code>,
<code>green</code>, <code>magenta</code>, <code>red</code> and <code>yellow</code>.
There are also <code>bold</code>, <code>italic</code>, <code>underline</code> and <code>inverse</code> codes.</p>
<h3>Custom <code>inspect()</code> function on Objects<span><a class="mark" href="#util_custom_inspect_function_on_objects" id="util_custom_inspect_function_on_objects">#</a></span></h3>
<!-- type=misc -->
<p>Objects also may define their own <code>inspect(depth)</code> function which <code>util.inspect()</code>
will invoke and use the result of when inspecting the object:</p>
<pre><code class="lang-js">const util = require('util');
var obj = { name: 'nate' };
obj.inspect = function(depth) {
return `{${this.name}}`;
};
util.inspect(obj);
// "{nate}"
</code></pre>
<p>You may also return another Object entirely, and the returned String will be
formatted according to the returned Object. This is similar to how
<code>JSON.stringify()</code> works:</p>
<pre><code class="lang-js">var obj = { foo: 'this will not show up in the inspect() output' };
obj.inspect = function(depth) {
return { bar: 'baz' };
};
util.inspect(obj);
// "{ bar: 'baz' }"
</code></pre>
<h2>util.isArray(object)<span><a class="mark" href="#util_util_isarray_object" id="util_util_isarray_object">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.6.0</span>
<span>Deprecated since: v4.0.0 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated</pre><p>Internal 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 "object" is an <code>Array</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="lang-js">const util = require('util');
util.isArray([])
// true
util.isArray(new Array)
// true
util.isArray({})
// false
</code></pre>
<h2>util.isBoolean(object)<span><a class="mark" href="#util_util_isboolean_object" id="util_util_isboolean_object">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.5</span>
<span>Deprecated since: v4.0.0 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is a <code>Boolean</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="lang-js">const util = require('util');
util.isBoolean(1)
// false
util.isBoolean(0)
// false
util.isBoolean(false)
// true
</code></pre>
<h2>util.isBuffer(object)<span><a class="mark" href="#util_util_isbuffer_object" id="util_util_isbuffer_object">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.5</span>
<span>Deprecated since: v4.0.0 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated: Use <a href="buffer.html#buffer_class_method_buffer_isbuffer_obj"><code>Buffer.isBuffer()</code></a> instead.</pre><p>Returns <code>true</code> if the given "object" is a <code>Buffer</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="lang-js">const util = require('util');
util.isBuffer({ length: 0 })
// false
util.isBuffer([])
// false
util.isBuffer(new Buffer('hello world'))
// true
</code></pre>
<h2>util.isDate(object)<span><a class="mark" href="#util_util_isdate_object" id="util_util_isdate_object">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.6.0</span>
<span>Deprecated since: v4.0.0 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is a <code>Date</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="lang-js">const util = require('util');
util.isDate(new Date())
// true
util.isDate(Date())
// false (without 'new' returns a String)
util.isDate({})
// false
</code></pre>
<h2>util.isError(object)<span><a class="mark" href="#util_util_iserror_object" id="util_util_iserror_object">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.6.0</span>
<span>Deprecated since: v4.0.0 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is an <a href="errors.html#errors_class_error"><code>Error</code></a>. Otherwise, returns
<code>false</code>.</p>
<pre><code class="lang-js">const util = require('util');
util.isError(new Error())
// true
util.isError(new TypeError())
// true
util.isError({ name: 'Error', message: 'an error occurred' })
// false
</code></pre>
<h2>util.isFunction(object)<span><a class="mark" href="#util_util_isfunction_object" id="util_util_isfunction_object">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.5</span>
<span>Deprecated since: v4.0.0 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is a <code>Function</code>. Otherwise, returns
<code>false</code>.</p>
<pre><code class="lang-js">const util = require('util');
function Foo() {}
var Bar = function() {};
util.isFunction({})
// false
util.isFunction(Foo)
// true
util.isFunction(Bar)
// true
</code></pre>
<h2>util.isNull(object)<span><a class="mark" href="#util_util_isnull_object" id="util_util_isnull_object">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.5</span>
<span>Deprecated since: v4.0.0 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is strictly <code>null</code>. Otherwise, returns
<code>false</code>.</p>
<pre><code class="lang-js">const util = require('util');
util.isNull(0)
// false
util.isNull(undefined)
// false
util.isNull(null)
// true
</code></pre>
<h2>util.isNullOrUndefined(object)<span><a class="mark" href="#util_util_isnullorundefined_object" id="util_util_isnullorundefined_object">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.5</span>
<span>Deprecated since: v4.0.0 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is <code>null</code> or <code>undefined</code>. Otherwise,
returns <code>false</code>.</p>
<pre><code class="lang-js">const util = require('util');
util.isNullOrUndefined(0)
// false
util.isNullOrUndefined(undefined)
// true
util.isNullOrUndefined(null)
// true
</code></pre>
<h2>util.isNumber(object)<span><a class="mark" href="#util_util_isnumber_object" id="util_util_isnumber_object">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.5</span>
<span>Deprecated since: v4.0.0 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is a <code>Number</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="lang-js">const util = require('util');
util.isNumber(false)
// false
util.isNumber(Infinity)
// true
util.isNumber(0)
// true
util.isNumber(NaN)
// true
</code></pre>
<h2>util.isObject(object)<span><a class="mark" href="#util_util_isobject_object" id="util_util_isobject_object">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.5</span>
<span>Deprecated since: v4.0.0 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is strictly an <code>Object</code> <strong>and</strong> not a
<code>Function</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="lang-js">const util = require('util');
util.isObject(5)
// false
util.isObject(null)
// false
util.isObject({})
// true
util.isObject(function(){})
// false
</code></pre>
<h2>util.isPrimitive(object)<span><a class="mark" href="#util_util_isprimitive_object" id="util_util_isprimitive_object">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.5</span>
<span>Deprecated since: v4.0.0 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is a primitive type. Otherwise, returns
<code>false</code>.</p>
<pre><code class="lang-js">const util = require('util');
util.isPrimitive(5)
// true
util.isPrimitive('foo')
// true
util.isPrimitive(false)
// true
util.isPrimitive(null)
// true
util.isPrimitive(undefined)
// true
util.isPrimitive({})
// false
util.isPrimitive(function() {})
// false
util.isPrimitive(/^$/)
// false
util.isPrimitive(new Date())
// false
</code></pre>
<h2>util.isRegExp(object)<span><a class="mark" href="#util_util_isregexp_object" id="util_util_isregexp_object">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.6.0</span>
<span>Deprecated since: v4.0.0 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is a <code>RegExp</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="lang-js">const util = require('util');
util.isRegExp(/some regexp/)
// true
util.isRegExp(new RegExp('another regexp'))
// true
util.isRegExp({})
// false
</code></pre>
<h2>util.isString(object)<span><a class="mark" href="#util_util_isstring_object" id="util_util_isstring_object">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.5</span>
<span>Deprecated since: v4.0.0 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is a <code>String</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="lang-js">const util = require('util');
util.isString('')
// true
util.isString('foo')
// true
util.isString(String('foo'))
// true
util.isString(5)
// false
</code></pre>
<h3>util.isSymbol(object)<span><a class="mark" href="#util_util_issymbol_object" id="util_util_issymbol_object">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.5</span>
<span>Deprecated since: v4.0.0 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is a <code>Symbol</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="lang-js">const util = require('util');
util.isSymbol(5)
// false
util.isSymbol('foo')
// false
util.isSymbol(Symbol('foo'))
// true
</code></pre>
<h2>util.isUndefined(object)<span><a class="mark" href="#util_util_isundefined_object" id="util_util_isundefined_object">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.5</span>
<span>Deprecated since: v4.0.0 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated</pre><p>Returns <code>true</code> if the given "object" is <code>undefined</code>. Otherwise, returns <code>false</code>.</p>
<pre><code class="lang-js">const util = require('util');
var foo;
util.isUndefined(5)
// false
util.isUndefined(foo)
// true
util.isUndefined(null)
// false
</code></pre>
<h2>util.log(string)<span><a class="mark" href="#util_util_log_string" id="util_util_log_string">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
<span>Deprecated since: v6.0.0 </span>
</div><p>Output with timestamp on <code>stdout</code>.</p>
<pre><code>require('util').log('Timestamped message.');
</code></pre><h2>util.print([...])<span><a class="mark" href="#util_util_print" id="util_util_print">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
<span>Deprecated since: v0.11.3 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated: Use <a href="console.html#console_console_log_data"><code>console.log()</code></a> instead.</pre><p>Deprecated predecessor of <code>console.log</code>.</p>
<h2>util.pump(readableStream, writableStream[, callback])<span><a class="mark" href="#util_util_pump_readablestream_writablestream_callback" id="util_util_pump_readablestream_writablestream_callback">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
<span>Deprecated since: v0.9.1 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated: Use readableStream.pipe(writableStream)</pre><p>Deprecated predecessor of <code>stream.pipe()</code>.</p>
<h2>util.puts([...])<span><a class="mark" href="#util_util_puts" id="util_util_puts">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.0</span>
<span>Deprecated since: v0.11.3 </span>
</div><pre class="api_stability api_stability_0">Stability: 0 - Deprecated: Use <a href="console.html#console_console_log_data"><code>console.log()</code></a> instead.</pre><p>Deprecated predecessor of <code>console.log</code>.</p>
<!-- [end-include:util.md] -->
<!-- [start-include:v8.md] -->
<h1>V8<span><a class="mark" href="#v8_v8" id="v8_v8">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>This module exposes events and interfaces specific to the version of <a href="https://developers.google.com/v8/">V8</a>
built with Node.js. These interfaces are subject to change by upstream and are
therefore not covered under the stability index.</p>
<h2>getHeapStatistics()<span><a class="mark" href="#v8_getheapstatistics" id="v8_getheapstatistics">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v1.0.0</span>
</div><p>Returns an object with the following properties</p>
<pre><code class="lang-js">{
total_heap_size: 7326976,
total_heap_size_executable: 4194304,
total_physical_size: 7326976,
total_available_size: 1152656,
used_heap_size: 3476208,
heap_size_limit: 1535115264
}
</code></pre>
<h2>getHeapSpaceStatistics()<span><a class="mark" href="#v8_getheapspacestatistics" id="v8_getheapspacestatistics">#</a></span></h2>
<p>Returns statistics about the V8 heap spaces, i.e. the segments which make up
the V8 heap. Order of heap spaces nor availability of a heap space can be
guaranteed as the statistics are provided via the V8 <code>GetHeapSpaceStatistics</code>
function.</p>
<p>Example result:</p>
<pre><code>[
{
"space_name": "new_space",
"space_size": 2063872,
"space_used_size": 951112,
"space_available_size": 80824,
"physical_space_size": 2063872
},
{
"space_name": "old_space",
"space_size": 3090560,
"space_used_size": 2493792,
"space_available_size": 0,
"physical_space_size": 3090560
},
{
"space_name": "code_space",
"space_size": 1260160,
"space_used_size": 644256,
"space_available_size": 960,
"physical_space_size": 1260160
},
{
"space_name": "map_space",
"space_size": 1094160,
"space_used_size": 201608,
"space_available_size": 0,
"physical_space_size": 1094160
},
{
"space_name": "large_object_space",
"space_size": 0,
"space_used_size": 0,
"space_available_size": 1490980608,
"physical_space_size": 0
}
]
</code></pre><h2>setFlagsFromString(string)<span><a class="mark" href="#v8_setflagsfromstring_string" id="v8_setflagsfromstring_string">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v1.0.0</span>
</div><p>Set additional V8 command line flags. Use 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>. An unofficial, community-maintained list of options
and their effects is available <a href="https://github.com/thlorenz/v8-flags/blob/master/flags-0.11.md">here</a>.</p>
<p>Usage:</p>
<pre><code class="lang-js">// Print GC events to stdout for one minute.
const v8 = require('v8');
v8.setFlagsFromString('--trace_gc');
setTimeout(function() { v8.setFlagsFromString('--notrace_gc'); }, 60e3);
</code></pre>
<!-- [end-include:v8.md] -->
<!-- [start-include:vm.md] -->
<h1>VM (Executing JavaScript)<span><a class="mark" href="#vm_vm_executing_javascript" id="vm_vm_executing_javascript">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><!--name=vm-->
<p>You can access this module with:</p>
<pre><code class="lang-js">const vm = require('vm');
</code></pre>
<p>JavaScript code can be compiled and run immediately or compiled, saved, and run
later.</p>
<h2>Class: Script<span><a class="mark" href="#vm_class_script" id="vm_class_script">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.1</span>
</div><p>A class for holding precompiled scripts, and running them in specific sandboxes.</p>
<h3>new vm.Script(code, options)<span><a class="mark" href="#vm_new_vm_script_code_options" id="vm_new_vm_script_code_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.1</span>
</div><p>Creating a new <code>Script</code> compiles <code>code</code> but does not run it. Instead, the
created <code>vm.Script</code> object represents this compiled code. This script can be run
later many times using methods below. The returned script is not bound to any
global object. It is bound before each run, just for that run.</p>
<p>The options when creating a script are:</p>
<ul>
<li><code>filename</code>: allows you to control the filename that shows up in any stack
traces produced from this script.</li>
<li><code>lineOffset</code>: allows you to add an offset to the line number that is
displayed in stack traces</li>
<li><code>columnOffset</code>: allows you to add an offset to the column number that is
displayed in stack traces</li>
<li><code>displayErrors</code>: whether or not to print any errors to stderr, with the
line of code that caused them highlighted, before throwing an exception.
Applies only to syntax errors compiling the code; errors while running the
code are controlled by the options to the script's methods.</li>
<li><code>timeout</code>: a number of milliseconds to execute <code>code</code> before terminating
execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a> will be thrown.</li>
</ul>
<h3>script.runInContext(contextifiedSandbox[, options])<span><a class="mark" href="#vm_script_runincontext_contextifiedsandbox_options" id="vm_script_runincontext_contextifiedsandbox_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.1</span>
</div><p>Similar to <a href="#vm_vm_runincontext_code_contextifiedsandbox_options"><code>vm.runInContext()</code></a> but a method of a precompiled <code>Script</code>
object. <code>script.runInContext()</code> runs <code>script</code>'s compiled code in
<code>contextifiedSandbox</code> and returns the result. Running code does not have access
to local scope.</p>
<p><code>script.runInContext()</code> takes the same options as
<a href="#vm_script_runinthiscontext_options"><code>script.runInThisContext()</code></a>.</p>
<p>Example: compile code that increments a global variable and sets one, then
execute the code multiple times. These globals are contained in the sandbox.</p>
<pre><code class="lang-js">const util = require('util');
const vm = require('vm');
var sandbox = {
animal: 'cat',
count: 2
};
var context = new vm.createContext(sandbox);
var script = new vm.Script('count += 1; name = "kitty"');
for (var i = 0; i < 10; ++i) {
script.runInContext(context);
}
console.log(util.inspect(sandbox));
// { animal: 'cat', count: 12, name: 'kitty' }
</code></pre>
<p>Note that running untrusted code is a tricky business requiring great care.
<code>script.runInContext()</code> is quite useful, but safely running untrusted code
requires a separate process.</p>
<h3>script.runInNewContext([sandbox][, options])<span><a class="mark" href="#vm_script_runinnewcontext_sandbox_options" id="vm_script_runinnewcontext_sandbox_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.1</span>
</div><p>Similar to <a href="#vm_vm_runinnewcontext_code_sandbox_options"><code>vm.runInNewContext()</code></a> but a method of a precompiled <code>Script</code>
object. <code>script.runInNewContext()</code> contextifies <code>sandbox</code> if passed or creates a
new contextified sandbox if it's omitted, and then runs <code>script</code>'s compiled code
with the sandbox as the global object and returns the result. Running code does
not have access to local scope.</p>
<p><code>script.runInNewContext()</code> takes the same options as
<a href="#vm_script_runinthiscontext_options"><code>script.runInThisContext()</code></a>.</p>
<p>Example: compile code that sets a global variable, then execute the code
multiple times in different contexts. These globals are set on and contained in
the sandboxes.</p>
<pre><code class="lang-js">const util = require('util');
const vm = require('vm');
const sandboxes = [{}, {}, {}];
const script = new vm.Script('globalVar = "set"');
sandboxes.forEach((sandbox) => {
script.runInNewContext(sandbox);
});
console.log(util.inspect(sandboxes));
// [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }]
</code></pre>
<p>Note that running untrusted code is a tricky business requiring great care.
<code>script.runInNewContext()</code> is quite useful, but safely running untrusted code
requires a separate process.</p>
<h3>script.runInThisContext(<a href="#zlib_class_options">options</a>)<span><a class="mark" href="#vm_script_runinthiscontext_options" id="vm_script_runinthiscontext_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.3.1</span>
</div><p>Similar to <a href=""><code>vm.runInThisContext()</code></a> but a method of a precompiled <code>Script</code>
object. <code>script.runInThisContext()</code> runs <code>script</code>'s compiled 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>Example of using <code>script.runInThisContext()</code> to compile code once and run it
multiple times:</p>
<pre><code class="lang-js">const vm = require('vm');
global.globalVar = 0;
const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' });
for (var i = 0; i < 1000; ++i) {
script.runInThisContext();
}
console.log(globalVar);
// 1000
</code></pre>
<p>The options for running a script are:</p>
<ul>
<li><code>filename</code>: allows you to control the filename that shows up in any stack
traces produced.</li>
<li><code>lineOffset</code>: allows you to add an offset to the line number that is
displayed in stack traces</li>
<li><code>columnOffset</code>: allows you to add an offset to the column number that is
displayed in stack traces</li>
<li><code>displayErrors</code>: whether or not to print any errors to stderr, with the
line of code that caused them highlighted, before throwing an exception.
Applies only to runtime errors executing the code; it is impossible to create
a <code>Script</code> instance with syntax errors, as the constructor will throw.</li>
<li><code>timeout</code>: a number of milliseconds to execute the script before terminating
execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a> will be thrown.</li>
</ul>
<h2>vm.createContext([sandbox])<span><a class="mark" href="#vm_vm_createcontext_sandbox" id="vm_vm_createcontext_sandbox">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.1</span>
</div><p>If given a <code>sandbox</code> object, will "contextify" that sandbox so that it can be
used in calls to <a href="#vm_vm_runincontext_code_contextifiedsandbox_options"><code>vm.runInContext()</code></a> or <a href="#vm_script_runincontext_contextifiedsandbox_options"><code>script.runInContext()</code></a>. Inside
scripts run as such, <code>sandbox</code> will be the global object, retaining all 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,
<code>sandbox</code> will be unchanged.</p>
<p>If not given a sandbox object, returns a new, empty contextified sandbox object
you can use.</p>
<p>This function is useful for creating a sandbox that can be used to run multiple
scripts, e.g. if you were emulating a web browser it could be used to create a
single sandbox representing a window's global object, then run all <code><script></code>
tags together inside that sandbox.</p>
<h2>vm.isContext(sandbox)<span><a class="mark" href="#vm_vm_iscontext_sandbox" id="vm_vm_iscontext_sandbox">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.7</span>
</div><p>Returns whether or not a sandbox object has been contextified by calling
<a href="#vm_vm_createcontext_sandbox"><code>vm.createContext()</code></a> on it.</p>
<h2>vm.runInContext(code, contextifiedSandbox[, options])<span><a class="mark" href="#vm_vm_runincontext_code_contextifiedsandbox_options" id="vm_vm_runincontext_code_contextifiedsandbox_options">#</a></span></h2>
<p><code>vm.runInContext()</code> compiles <code>code</code>, then runs it in <code>contextifiedSandbox</code> and
returns the result. Running code does not have access to local scope. The
<code>contextifiedSandbox</code> object must have been previously contextified via
<a href="#vm_vm_createcontext_sandbox"><code>vm.createContext()</code></a>; it will be used as the global object for <code>code</code>.</p>
<p><code>vm.runInContext()</code> takes the same options as <a href="#vm_vm_runinthiscontext_code_options"><code>vm.runInThisContext()</code></a>.</p>
<p>Example: compile and execute different scripts in a single existing context.</p>
<pre><code class="lang-js">const util = require('util');
const vm = require('vm');
const sandbox = { globalVar: 1 };
vm.createContext(sandbox);
for (var i = 0; i < 10; ++i) {
vm.runInContext('globalVar *= 2;', sandbox);
}
console.log(util.inspect(sandbox));
// { globalVar: 1024 }
</code></pre>
<p>Note that running untrusted code is a tricky business requiring great care.
<code>vm.runInContext()</code> is quite useful, but safely running untrusted code requires
a separate process.</p>
<h2>vm.runInDebugContext(code)<span><a class="mark" href="#vm_vm_runindebugcontext_code" id="vm_vm_runindebugcontext_code">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.14</span>
</div><p><code>vm.runInDebugContext()</code> compiles and executes <code>code</code> inside the V8 debug
context. The primary use case is to get access to the V8 debug object:</p>
<pre><code class="lang-js">const vm = require('vm');
const Debug = vm.runInDebugContext('Debug');
console.log(Debug.findScript(process.emit).name); // 'events.js'
console.log(Debug.findScript(process.exit).name); // 'internal/process.js'
</code></pre>
<p>Note that the debug context and object are intrinsically tied to V8's debugger
implementation and may change (or even get removed) without prior warning.</p>
<p>The debug object can also be exposed with the <code>--expose_debug_as=</code> switch.</p>
<h2>vm.runInNewContext(code[, sandbox][, options])<span><a class="mark" href="#vm_vm_runinnewcontext_code_sandbox_options" id="vm_vm_runinnewcontext_code_sandbox_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.1</span>
</div><p><code>vm.runInNewContext()</code> compiles <code>code</code>, contextifies <code>sandbox</code> if passed or
creates a new contextified sandbox if it's omitted, and then runs the code with
the sandbox as the global object and returns the result.</p>
<p><code>vm.runInNewContext()</code> takes the same options as <a href="#vm_vm_runinthiscontext_code_options"><code>vm.runInThisContext()</code></a>.</p>
<p>Example: compile and execute code that increments a global variable and sets a
new one. These globals are contained in the sandbox.</p>
<pre><code class="lang-js">const util = require('util');
const vm = require('vm');
const sandbox = {
animal: 'cat',
count: 2
};
vm.runInNewContext('count += 1; name = "kitty"', sandbox);
console.log(util.inspect(sandbox));
// { animal: 'cat', count: 3, name: 'kitty' }
</code></pre>
<p>Note that running untrusted code is a tricky business requiring great care.
<code>vm.runInNewContext()</code> is quite useful, but safely running untrusted code requires
a separate process.</p>
<h2>vm.runInThisContext(code[, options])<span><a class="mark" href="#vm_vm_runinthiscontext_code_options" id="vm_vm_runinthiscontext_code_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.3.1</span>
</div><p><code>vm.runInThisContext()</code> compiles <code>code</code>, runs it 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>Example of using <code>vm.runInThisContext()</code> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval"><code>eval()</code></a> to run the same code:</p>
<pre><code class="lang-js">const vm = require('vm');
var localVar = 'initial value';
const vmResult = vm.runInThisContext('localVar = "vm";');
console.log('vmResult:', vmResult);
console.log('localVar:', localVar);
const evalResult = eval('localVar = "eval";');
console.log('evalResult:', evalResult);
console.log('localVar:', localVar);
// vmResult: 'vm', localVar: 'initial value'
// evalResult: 'eval', localVar: 'eval'
</code></pre>
<p><code>vm.runInThisContext()</code> does not have access to the local scope, so <code>localVar</code>
is unchanged. <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval"><code>eval()</code></a> does have access to the local scope, so <code>localVar</code> is
changed.</p>
<p>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>. However, it also has the following additional options:</p>
<ul>
<li><code>filename</code>: allows you to control the filename that shows up in any stack
traces produced.</li>
<li><code>lineOffset</code>: allows you to add an offset to the line number that is
displayed in stack traces</li>
<li><code>columnOffset</code>: allows you to add an offset to the column number that is
displayed in stack traces</li>
<li><code>displayErrors</code>: whether or not to print any errors to stderr, with the
line of code that caused them highlighted, before throwing an exception.
Will capture both syntax errors from compiling <code>code</code> and runtime errors
thrown by executing the compiled code. Defaults to <code>true</code>.</li>
<li><code>timeout</code>: a number of milliseconds to execute <code>code</code> before terminating
execution. If execution is terminated, an <a href="errors.html#errors_class_error"><code>Error</code></a> will be thrown.</li>
</ul>
<h2>Example: Run a Server within a VM<span><a class="mark" href="#vm_example_run_a_server_within_a_vm" id="vm_example_run_a_server_within_a_vm">#</a></span></h2>
<p>The context of <code>.runInThisContext()</code> refers to the V8 context. The code passed
to this VM context will have it's own isolated scope. To run a simple web server
using the <code>http</code> module, for instance, the code passed to the context must either
call <code>require('http')</code> on its own, or have a reference to the <code>http</code> module passed
to it. For instance:</p>
<pre><code class="lang-js">'use strict';
const vm = require('vm');
let code =
`(function(require) {
const http = require('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/');
})`;
vm.runInThisContext(code)(require);
</code></pre>
<p><em>Note: <code>require()</code> in the above case shares the state with context it is passed
from. This might introduce risks when unknown code is executed, e.g. altering
objects from the calling thread's context in unwanted ways. It is advisable to
run <code>vm</code> code in a separate process.</em></p>
<!-- [end-include:vm.md] -->
<!-- [start-include:zlib.md] -->
<h1>Zlib<span><a class="mark" href="#zlib_zlib" id="zlib_zlib">#</a></span></h1>
<pre class="api_stability api_stability_2">Stability: 2 - Stable</pre><p>You can access this module with:</p>
<pre><code>const zlib = require('zlib');
</code></pre><p>This provides bindings to Gzip/Gunzip, Deflate/Inflate, and
DeflateRaw/InflateRaw classes. Each class takes the same options, and
is a readable/writable Stream.</p>
<h2>Examples<span><a class="mark" href="#zlib_examples" id="zlib_examples">#</a></span></h2>
<p>Compressing or decompressing a file can be done by piping an
fs.ReadStream into a zlib stream, then into an fs.WriteStream.</p>
<pre><code class="lang-js">const gzip = zlib.createGzip();
const fs = require('fs');
const inp = fs.createReadStream('input.txt');
const out = fs.createWriteStream('input.txt.gz');
inp.pipe(gzip).pipe(out);
</code></pre>
<p>Compressing or decompressing data in one step can be done by using
the convenience methods.</p>
<pre><code class="lang-js">const input = '.................................';
zlib.deflate(input, (err, buffer) => {
if (!err) {
console.log(buffer.toString('base64'));
} else {
// handle error
}
});
const buffer = new Buffer('eJzT0yMAAGTvBe8=', 'base64');
zlib.unzip(buffer, (err, buffer) => {
if (!err) {
console.log(buffer.toString());
} else {
// handle error
}
});
</code></pre>
<p>To use this module in an HTTP client or server, use the <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3">accept-encoding</a>
on requests, and the <a href="https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.11">content-encoding</a> header on responses.</p>
<p><strong>Note: these examples are drastically simplified to show
the basic concept.</strong> Zlib encoding can be expensive, and the results
ought to be cached. See <a href="#zlib_memory_usage_tuning">Memory Usage Tuning</a> for more information
on the speed/memory/compression tradeoffs involved in zlib usage.</p>
<pre><code class="lang-js">// client request example
const zlib = require('zlib');
const http = require('http');
const fs = require('fs');
const request = http.get({ host: 'izs.me',
path: '/',
port: 80,
headers: { 'accept-encoding': 'gzip,deflate' } });
request.on('response', (response) => {
var output = fs.createWriteStream('izs.me_index.html');
switch (response.headers['content-encoding']) {
// or, just use zlib.createUnzip() to handle both cases
case 'gzip':
response.pipe(zlib.createGunzip()).pipe(output);
break;
case 'deflate':
response.pipe(zlib.createInflate()).pipe(output);
break;
default:
response.pipe(output);
break;
}
});
// server example
// Running a gzip operation on every request is quite expensive.
// It would be much more efficient to cache the compressed buffer.
const zlib = require('zlib');
const http = require('http');
const fs = require('fs');
http.createServer((request, response) => {
var raw = fs.createReadStream('index.html');
var acceptEncoding = request.headers['accept-encoding'];
if (!acceptEncoding) {
acceptEncoding = '';
}
// Note: this is not a conformant accept-encoding parser.
// See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
if (acceptEncoding.match(/\bdeflate\b/)) {
response.writeHead(200, { 'content-encoding': 'deflate' });
raw.pipe(zlib.createDeflate()).pipe(response);
} else if (acceptEncoding.match(/\bgzip\b/)) {
response.writeHead(200, { 'content-encoding': 'gzip' });
raw.pipe(zlib.createGzip()).pipe(response);
} else {
response.writeHead(200, {});
raw.pipe(response);
}
}).listen(1337);
</code></pre>
<h2>Memory Usage Tuning<span><a class="mark" href="#zlib_memory_usage_tuning" id="zlib_memory_usage_tuning">#</a></span></h2>
<!--type=misc-->
<p>From <code>zlib/zconf.h</code>, modified to node.js's usage:</p>
<p>The memory requirements for deflate are (in bytes):</p>
<pre><code>(1 << (windowBits+2)) + (1 << (memLevel+9))
</code></pre><p>that is: 128K for windowBits=15 + 128K for memLevel = 8
(default values) plus a few kilobytes for small objects.</p>
<p>For example, if you want to reduce
the default memory requirements from 256K to 128K, set the options to:</p>
<pre><code>{ windowBits: 14, memLevel: 7 }
</code></pre><p>Of course this will generally degrade compression (there's no free lunch).</p>
<p>The memory requirements for inflate are (in bytes)</p>
<pre><code>1 << windowBits
</code></pre><p>that is, 32K for windowBits=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 zlib 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 zlib, since it'll be able to process more data in a
single <code>write</code> operation. So, this is another factor that affects the
speed, at the cost of memory usage.</p>
<h2>Flushing<span><a class="mark" href="#zlib_flushing" id="zlib_flushing">#</a></span></h2>
<p>Calling <a href="#zlib_zlib_flush_kind_callback"><code>.flush()</code></a> on a compression stream will make zlib 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><code class="lang-js">const zlib = require('zlib');
const http = require('http');
http.createServer((request, response) => {
// For the sake of simplicity, the Accept-Encoding checks are omitted.
response.writeHead(200, { 'content-encoding': 'gzip' });
const output = zlib.createGzip();
output.pipe(response);
setInterval(() => {
output.write(`The current time is ${Date()}\n`, () => {
// The data has been passed to zlib, but the compression algorithm may
// have decided to buffer the data for more efficient compression.
// Calling .flush() will make the data available as soon as the client
// is ready to receive it.
output.flush();
});
}, 1000);
}).listen(1337);
</code></pre>
<h2>Constants<span><a class="mark" href="#zlib_constants" id="zlib_constants">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><!--type=misc-->
<p>All of the constants defined in zlib.h are also defined on
<code>require('zlib')</code>.
In the normal course of operations, you will not need to ever set any of
these. They are documented here so that their presence is not
surprising. This section is taken almost directly from the
<a href="http://zlib.net/manual.html#Constants">zlib documentation</a>. See <a href="http://zlib.net/manual.html#Constants">http://zlib.net/manual.html#Constants</a> for more
details.</p>
<p>Allowed flush values.</p>
<ul>
<li><code>zlib.Z_NO_FLUSH</code></li>
<li><code>zlib.Z_PARTIAL_FLUSH</code></li>
<li><code>zlib.Z_SYNC_FLUSH</code></li>
<li><code>zlib.Z_FULL_FLUSH</code></li>
<li><code>zlib.Z_FINISH</code></li>
<li><code>zlib.Z_BLOCK</code></li>
<li><code>zlib.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.Z_OK</code></li>
<li><code>zlib.Z_STREAM_END</code></li>
<li><code>zlib.Z_NEED_DICT</code></li>
<li><code>zlib.Z_ERRNO</code></li>
<li><code>zlib.Z_STREAM_ERROR</code></li>
<li><code>zlib.Z_DATA_ERROR</code></li>
<li><code>zlib.Z_MEM_ERROR</code></li>
<li><code>zlib.Z_BUF_ERROR</code></li>
<li><code>zlib.Z_VERSION_ERROR</code></li>
</ul>
<p>Compression levels.</p>
<ul>
<li><code>zlib.Z_NO_COMPRESSION</code></li>
<li><code>zlib.Z_BEST_SPEED</code></li>
<li><code>zlib.Z_BEST_COMPRESSION</code></li>
<li><code>zlib.Z_DEFAULT_COMPRESSION</code></li>
</ul>
<p>Compression strategy.</p>
<ul>
<li><code>zlib.Z_FILTERED</code></li>
<li><code>zlib.Z_HUFFMAN_ONLY</code></li>
<li><code>zlib.Z_RLE</code></li>
<li><code>zlib.Z_FIXED</code></li>
<li><code>zlib.Z_DEFAULT_STRATEGY</code></li>
</ul>
<p>The deflate compression method (the only one supported in this version).</p>
<ul>
<li><code>zlib.Z_DEFLATED</code></li>
</ul>
<p>For initializing zalloc, zfree, opaque.</p>
<ul>
<li><code>zlib.Z_NULL</code></li>
</ul>
<h2>Class Options<span><a class="mark" href="#zlib_class_options" id="zlib_class_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.11.1</span>
</div><!--type=misc-->
<p>Each class takes an options object. All options are optional.</p>
<p>Note that some options are only relevant when compressing, and are
ignored by the decompression classes.</p>
<ul>
<li>flush (default: <code>zlib.Z_NO_FLUSH</code>)</li>
<li>chunkSize (default: 16*1024)</li>
<li>windowBits</li>
<li>level (compression only)</li>
<li>memLevel (compression only)</li>
<li>strategy (compression only)</li>
<li>dictionary (deflate/inflate only, empty dictionary by default)</li>
</ul>
<p>See the description of <code>deflateInit2</code> and <code>inflateInit2</code> at
<a href="http://zlib.net/manual.html#Advanced">http://zlib.net/manual.html#Advanced</a> for more information on these.</p>
<h2>Class: zlib.Deflate<span><a class="mark" href="#zlib_class_zlib_deflate" id="zlib_class_zlib_deflate">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><p>Compress data using deflate.</p>
<h2>Class: zlib.DeflateRaw<span><a class="mark" href="#zlib_class_zlib_deflateraw" id="zlib_class_zlib_deflateraw">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><p>Compress data using deflate, and do not append a zlib header.</p>
<h2>Class: zlib.Gunzip<span><a class="mark" href="#zlib_class_zlib_gunzip" id="zlib_class_zlib_gunzip">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><p>Decompress a gzip stream.</p>
<h2>Class: zlib.Gzip<span><a class="mark" href="#zlib_class_zlib_gzip" id="zlib_class_zlib_gzip">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><p>Compress data using gzip.</p>
<h2>Class: zlib.Inflate<span><a class="mark" href="#zlib_class_zlib_inflate" id="zlib_class_zlib_inflate">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><p>Decompress a deflate stream.</p>
<h2>Class: zlib.InflateRaw<span><a class="mark" href="#zlib_class_zlib_inflateraw" id="zlib_class_zlib_inflateraw">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><p>Decompress a raw deflate stream.</p>
<h2>Class: zlib.Unzip<span><a class="mark" href="#zlib_class_zlib_unzip" id="zlib_class_zlib_unzip">#</a></span></h2>
<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>
<h2>Class: zlib.Zlib<span><a class="mark" href="#zlib_class_zlib_zlib" id="zlib_class_zlib_zlib">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><p>Not exported by the <code>zlib</code> module. It is documented here because it is the base
class of the compressor/decompressor classes.</p>
<h3>zlib.flush([kind], callback)<span><a class="mark" href="#zlib_zlib_flush_kind_callback" id="zlib_zlib_flush_kind_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><p><code>kind</code> defaults to <code>zlib.Z_FULL_FLUSH</code>.</p>
<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 zlib 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>
<h3>zlib.params(level, strategy, callback)<span><a class="mark" href="#zlib_zlib_params_level_strategy_callback" id="zlib_zlib_params_level_strategy_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.4</span>
</div><p>Dynamically update the compression level and compression strategy.
Only applicable to deflate algorithm.</p>
<h3>zlib.reset()<span><a class="mark" href="#zlib_zlib_reset" id="zlib_zlib_reset">#</a></span></h3>
<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>
<h2>zlib.createDeflate(<a href="#zlib_class_options">options</a>)<span><a class="mark" href="#zlib_zlib_createdeflate_options" id="zlib_zlib_createdeflate_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><p>Returns a new <a href="#zlib_class_zlib_deflate">Deflate</a> object with an <a href="#zlib_class_options">options</a>.</p>
<h2>zlib.createDeflateRaw(<a href="#zlib_class_options">options</a>)<span><a class="mark" href="#zlib_zlib_createdeflateraw_options" id="zlib_zlib_createdeflateraw_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><p>Returns a new <a href="#zlib_class_zlib_deflateraw">DeflateRaw</a> object with an <a href="#zlib_class_options">options</a>.</p>
<h2>zlib.createGunzip(<a href="#zlib_class_options">options</a>)<span><a class="mark" href="#zlib_zlib_creategunzip_options" id="zlib_zlib_creategunzip_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><p>Returns a new <a href="#zlib_class_zlib_gunzip">Gunzip</a> object with an <a href="#zlib_class_options">options</a>.</p>
<h2>zlib.createGzip(<a href="#zlib_class_options">options</a>)<span><a class="mark" href="#zlib_zlib_creategzip_options" id="zlib_zlib_creategzip_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><p>Returns a new <a href="#zlib_class_zlib_gzip">Gzip</a> object with an <a href="#zlib_class_options">options</a>.</p>
<h2>zlib.createInflate(<a href="#zlib_class_options">options</a>)<span><a class="mark" href="#zlib_zlib_createinflate_options" id="zlib_zlib_createinflate_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><p>Returns a new <a href="#zlib_class_zlib_inflate">Inflate</a> object with an <a href="#zlib_class_options">options</a>.</p>
<h2>zlib.createInflateRaw(<a href="#zlib_class_options">options</a>)<span><a class="mark" href="#zlib_zlib_createinflateraw_options" id="zlib_zlib_createinflateraw_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><p>Returns a new <a href="#zlib_class_zlib_inflateraw">InflateRaw</a> object with an <a href="#zlib_class_options">options</a>.</p>
<h2>zlib.createUnzip(<a href="#zlib_class_options">options</a>)<span><a class="mark" href="#zlib_zlib_createunzip_options" id="zlib_zlib_createunzip_options">#</a></span></h2>
<div class="api_metadata">
<span>Added in: v0.5.8</span>
</div><p>Returns a new <a href="#zlib_class_zlib_unzip">Unzip</a> object with an <a href="#zlib_class_options">options</a>.</p>
<h2>Convenience Methods<span><a class="mark" href="#zlib_convenience_methods" id="zlib_convenience_methods">#</a></span></h2>
<!--type=misc-->
<p>All of these take a <a href="buffer.html">Buffer</a> or string as the first argument, an optional second
argument to supply options to the zlib 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>
<h3>zlib.deflate(buf[, options], callback)<span><a class="mark" href="#zlib_zlib_deflate_buf_options_callback" id="zlib_zlib_deflate_buf_options_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.6.0</span>
</div><h3>zlib.deflateSync(buf[, options])<span><a class="mark" href="#zlib_zlib_deflatesync_buf_options" id="zlib_zlib_deflatesync_buf_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.12</span>
</div><p>Compress a <a href="buffer.html">Buffer</a> or string with <a href="#zlib_class_zlib_deflate">Deflate</a>.</p>
<h3>zlib.deflateRaw(buf[, options], callback)<span><a class="mark" href="#zlib_zlib_deflateraw_buf_options_callback" id="zlib_zlib_deflateraw_buf_options_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.6.0</span>
</div><h3>zlib.deflateRawSync(buf[, options])<span><a class="mark" href="#zlib_zlib_deflaterawsync_buf_options" id="zlib_zlib_deflaterawsync_buf_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.12</span>
</div><p>Compress a <a href="buffer.html">Buffer</a> or string with <a href="#zlib_class_zlib_deflateraw">DeflateRaw</a>.</p>
<h3>zlib.gunzip(buf[, options], callback)<span><a class="mark" href="#zlib_zlib_gunzip_buf_options_callback" id="zlib_zlib_gunzip_buf_options_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.6.0</span>
</div><h3>zlib.gunzipSync(buf[, options])<span><a class="mark" href="#zlib_zlib_gunzipsync_buf_options" id="zlib_zlib_gunzipsync_buf_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.12</span>
</div><p>Decompress a <a href="buffer.html">Buffer</a> or string with <a href="#zlib_class_zlib_gunzip">Gunzip</a>.</p>
<h3>zlib.gzip(buf[, options], callback)<span><a class="mark" href="#zlib_zlib_gzip_buf_options_callback" id="zlib_zlib_gzip_buf_options_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.6.0</span>
</div><h3>zlib.gzipSync(buf[, options])<span><a class="mark" href="#zlib_zlib_gzipsync_buf_options" id="zlib_zlib_gzipsync_buf_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.12</span>
</div><p>Compress a <a href="buffer.html">Buffer</a> or string with <a href="#zlib_class_zlib_gzip">Gzip</a>.</p>
<h3>zlib.inflate(buf[, options], callback)<span><a class="mark" href="#zlib_zlib_inflate_buf_options_callback" id="zlib_zlib_inflate_buf_options_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.6.0</span>
</div><h3>zlib.inflateSync(buf[, options])<span><a class="mark" href="#zlib_zlib_inflatesync_buf_options" id="zlib_zlib_inflatesync_buf_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.12</span>
</div><p>Decompress a <a href="buffer.html">Buffer</a> or string with <a href="#zlib_class_zlib_inflate">Inflate</a>.</p>
<h3>zlib.inflateRaw(buf[, options], callback)<span><a class="mark" href="#zlib_zlib_inflateraw_buf_options_callback" id="zlib_zlib_inflateraw_buf_options_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.6.0</span>
</div><h3>zlib.inflateRawSync(buf[, options])<span><a class="mark" href="#zlib_zlib_inflaterawsync_buf_options" id="zlib_zlib_inflaterawsync_buf_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.12</span>
</div><p>Decompress a <a href="buffer.html">Buffer</a> or string with <a href="#zlib_class_zlib_inflateraw">InflateRaw</a>.</p>
<h3>zlib.unzip(buf[, options], callback)<span><a class="mark" href="#zlib_zlib_unzip_buf_options_callback" id="zlib_zlib_unzip_buf_options_callback">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.6.0</span>
</div><h3>zlib.unzipSync(buf[, options])<span><a class="mark" href="#zlib_zlib_unzipsync_buf_options" id="zlib_zlib_unzipsync_buf_options">#</a></span></h3>
<div class="api_metadata">
<span>Added in: v0.11.12</span>
</div><p>Decompress a <a href="buffer.html">Buffer</a> or string with <a href="#zlib_class_zlib_unzip">Unzip</a>.</p>
<!-- [end-include:zlib.md] -->
</div>
</div>
</div>
<script src="assets/sh_main.js"></script>
<script src="assets/sh_javascript.min.js"></script>
<script>highlight(undefined, undefined, 'pre');</script>
<!-- __TRACKING__ -->
</body>
</html>
|