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
|
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>About this Documentation Node.js v0.10.29 Manual & Documentation</title>
<link rel="stylesheet" href="assets/style.css">
<link rel="stylesheet" href="assets/sh.css">
<link rel="canonical" href="http://nodejs.org/api/all.html">
</head>
<body class="alt apidoc" id="api-section-all">
<div id="intro" class="interior">
<a href="/" title="Go back to the home page">
<img id="logo" src="http://nodejs.org/images/logo-light.png" alt="node.js">
</a>
</div>
<div id="content" class="clearfix">
<div id="column2" class="interior">
<ul>
<li><a href="/" class="home">Home</a></li>
<li><a href="/download/" class="download">Download</a></li>
<li><a href="/about/" class="about">About</a></li>
<li><a href="http://npmjs.org/" class="npm">npm Registry</a></li>
<li><a href="http://nodejs.org/api/" class="docs current">Docs</a></li>
<li><a href="http://blog.nodejs.org" class="blog">Blog</a></li>
<li><a href="/community/" class="community">Community</a></li>
<li><a href="/logos/" class="logos">Logos</a></li>
<li><a href="http://jobs.nodejs.org/" class="jobs">Jobs</a></li>
</ul>
<p class="twitter"><a href="http://twitter.com/nodejs">@nodejs</a></p>
</div>
<div id="column1" class="interior">
<header>
<h1>Node.js v0.10.29 Manual & 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><a href="#all_about_this_documentation">About this Documentation</a><ul>
<li><a href="#all_stability_index">Stability Index</a></li>
<li><a href="#all_json_output">JSON Output</a></li>
</ul>
</li>
<li><a href="#all_synopsis">Synopsis</a></li>
<li><a href="#all_global_objects">Global Objects</a><ul>
<li><a href="#all_global">global</a></li>
<li><a href="#all_process">process</a></li>
<li><a href="#all_console">console</a></li>
<li><a href="#all_class_buffer">Class: Buffer</a></li>
<li><a href="#all_require">require()</a><ul>
<li><a href="#all_require_resolve">require.resolve()</a></li>
<li><a href="#all_require_cache">require.cache</a></li>
<li><a href="#all_require_extensions">require.extensions</a></li>
</ul>
</li>
<li><a href="#all_filename">__filename</a></li>
<li><a href="#all_dirname">__dirname</a></li>
<li><a href="#all_module">module</a></li>
<li><a href="#all_exports">exports</a></li>
<li><a href="#all_settimeout_cb_ms">setTimeout(cb, ms)</a></li>
<li><a href="#all_cleartimeout_t">clearTimeout(t)</a></li>
<li><a href="#all_setinterval_cb_ms">setInterval(cb, ms)</a></li>
<li><a href="#all_clearinterval_t">clearInterval(t)</a></li>
</ul>
</li>
<li><a href="#all_console_1">console</a><ul>
<li><a href="#all_console_log_data">console.log([data], [...])</a></li>
<li><a href="#all_console_info_data">console.info([data], [...])</a></li>
<li><a href="#all_console_error_data">console.error([data], [...])</a></li>
<li><a href="#all_console_warn_data">console.warn([data], [...])</a></li>
<li><a href="#all_console_dir_obj">console.dir(obj)</a></li>
<li><a href="#all_console_time_label">console.time(label)</a></li>
<li><a href="#all_console_timeend_label">console.timeEnd(label)</a></li>
<li><a href="#all_console_trace_label">console.trace(label)</a></li>
<li><a href="#all_console_assert_expression_message">console.assert(expression, [message])</a></li>
</ul>
</li>
<li><a href="#all_timers">Timers</a><ul>
<li><a href="#all_settimeout_callback_delay_arg">setTimeout(callback, delay, [arg], [...])</a></li>
<li><a href="#all_cleartimeout_timeoutobject">clearTimeout(timeoutObject)</a></li>
<li><a href="#all_setinterval_callback_delay_arg">setInterval(callback, delay, [arg], [...])</a></li>
<li><a href="#all_clearinterval_intervalobject">clearInterval(intervalObject)</a></li>
<li><a href="#all_unref">unref()</a></li>
<li><a href="#all_ref">ref()</a></li>
<li><a href="#all_setimmediate_callback_arg">setImmediate(callback, [arg], [...])</a></li>
<li><a href="#all_clearimmediate_immediateobject">clearImmediate(immediateObject)</a></li>
</ul>
</li>
<li><a href="#all_modules">Modules</a><ul>
<li><a href="#all_cycles">Cycles</a></li>
<li><a href="#all_core_modules">Core Modules</a></li>
<li><a href="#all_file_modules">File Modules</a></li>
<li><a href="#all_loading_from_node_modules_folders">Loading from <code>node_modules</code> Folders</a></li>
<li><a href="#all_folders_as_modules">Folders as Modules</a></li>
<li><a href="#all_caching">Caching</a><ul>
<li><a href="#all_module_caching_caveats">Module Caching Caveats</a></li>
</ul>
</li>
<li><a href="#all_the_module_object">The <code>module</code> Object</a><ul>
<li><a href="#all_module_exports">module.exports</a><ul>
<li><a href="#all_exports_alias">exports alias</a></li>
</ul>
</li>
<li><a href="#all_module_require_id">module.require(id)</a></li>
<li><a href="#all_module_id">module.id</a></li>
<li><a href="#all_module_filename">module.filename</a></li>
<li><a href="#all_module_loaded">module.loaded</a></li>
<li><a href="#all_module_parent">module.parent</a></li>
<li><a href="#all_module_children">module.children</a></li>
</ul>
</li>
<li><a href="#all_all_together">All Together...</a></li>
<li><a href="#all_loading_from_the_global_folders">Loading from the global folders</a></li>
<li><a href="#all_accessing_the_main_module">Accessing the main module</a></li>
<li><a href="#all_addenda_package_manager_tips">Addenda: Package Manager Tips</a></li>
</ul>
</li>
<li><a href="#all_addons">Addons</a><ul>
<li><a href="#all_hello_world">Hello world</a></li>
<li><a href="#all_addon_patterns">Addon patterns</a><ul>
<li><a href="#all_function_arguments">Function arguments</a></li>
<li><a href="#all_callbacks">Callbacks</a></li>
<li><a href="#all_object_factory">Object factory</a></li>
<li><a href="#all_function_factory">Function factory</a></li>
<li><a href="#all_wrapping_c_objects">Wrapping C++ objects</a></li>
<li><a href="#all_factory_of_wrapped_objects">Factory of wrapped objects</a></li>
<li><a href="#all_passing_wrapped_objects_around">Passing wrapped objects around</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_process_1">process</a><ul>
<li><a href="#all_event_exit">Event: 'exit'</a></li>
<li><a href="#all_event_uncaughtexception">Event: 'uncaughtException'</a></li>
<li><a href="#all_signal_events">Signal Events</a></li>
<li><a href="#all_process_stdout">process.stdout</a></li>
<li><a href="#all_process_stderr">process.stderr</a></li>
<li><a href="#all_process_stdin">process.stdin</a></li>
<li><a href="#all_process_argv">process.argv</a></li>
<li><a href="#all_process_execpath">process.execPath</a></li>
<li><a href="#all_process_execargv">process.execArgv</a></li>
<li><a href="#all_process_abort">process.abort()</a></li>
<li><a href="#all_process_chdir_directory">process.chdir(directory)</a></li>
<li><a href="#all_process_cwd">process.cwd()</a></li>
<li><a href="#all_process_env">process.env</a></li>
<li><a href="#all_process_exit_code">process.exit([code])</a></li>
<li><a href="#all_process_getgid">process.getgid()</a></li>
<li><a href="#all_process_setgid_id">process.setgid(id)</a></li>
<li><a href="#all_process_getuid">process.getuid()</a></li>
<li><a href="#all_process_setuid_id">process.setuid(id)</a></li>
<li><a href="#all_process_getgroups">process.getgroups()</a></li>
<li><a href="#all_process_setgroups_groups">process.setgroups(groups)</a></li>
<li><a href="#all_process_initgroups_user_extra_group">process.initgroups(user, extra_group)</a></li>
<li><a href="#all_process_version">process.version</a></li>
<li><a href="#all_process_versions">process.versions</a></li>
<li><a href="#all_process_config">process.config</a></li>
<li><a href="#all_process_kill_pid_signal">process.kill(pid, [signal])</a></li>
<li><a href="#all_process_pid">process.pid</a></li>
<li><a href="#all_process_title">process.title</a></li>
<li><a href="#all_process_arch">process.arch</a></li>
<li><a href="#all_process_platform">process.platform</a></li>
<li><a href="#all_process_memoryusage">process.memoryUsage()</a></li>
<li><a href="#all_process_nexttick_callback">process.nextTick(callback)</a></li>
<li><a href="#all_process_maxtickdepth">process.maxTickDepth</a></li>
<li><a href="#all_process_umask_mask">process.umask([mask])</a></li>
<li><a href="#all_process_uptime">process.uptime()</a></li>
<li><a href="#all_process_hrtime">process.hrtime()</a></li>
</ul>
</li>
<li><a href="#all_util">util</a><ul>
<li><a href="#all_util_format_format">util.format(format, [...])</a></li>
<li><a href="#all_util_debug_string">util.debug(string)</a></li>
<li><a href="#all_util_error">util.error([...])</a></li>
<li><a href="#all_util_puts">util.puts([...])</a></li>
<li><a href="#all_util_print">util.print([...])</a></li>
<li><a href="#all_util_log_string">util.log(string)</a></li>
<li><a href="#all_util_inspect_object_options">util.inspect(object, [options])</a><ul>
<li><a href="#all_customizing_util_inspect_colors">Customizing <code>util.inspect</code> colors</a></li>
</ul>
</li>
<li><a href="#all_util_isarray_object">util.isArray(object)</a></li>
<li><a href="#all_util_isregexp_object">util.isRegExp(object)</a></li>
<li><a href="#all_util_isdate_object">util.isDate(object)</a></li>
<li><a href="#all_util_iserror_object">util.isError(object)</a></li>
<li><a href="#all_util_pump_readablestream_writablestream_callback">util.pump(readableStream, writableStream, [callback])</a></li>
<li><a href="#all_util_inherits_constructor_superconstructor">util.inherits(constructor, superConstructor)</a></li>
</ul>
</li>
<li><a href="#all_events">Events</a><ul>
<li><a href="#all_class_events_eventemitter">Class: events.EventEmitter</a><ul>
<li><a href="#all_emitter_addlistener_event_listener">emitter.addListener(event, listener)</a></li>
<li><a href="#all_emitter_on_event_listener">emitter.on(event, listener)</a></li>
<li><a href="#all_emitter_once_event_listener">emitter.once(event, listener)</a></li>
<li><a href="#all_emitter_removelistener_event_listener">emitter.removeListener(event, listener)</a></li>
<li><a href="#all_emitter_removealllisteners_event">emitter.removeAllListeners([event])</a></li>
<li><a href="#all_emitter_setmaxlisteners_n">emitter.setMaxListeners(n)</a></li>
<li><a href="#all_emitter_listeners_event">emitter.listeners(event)</a></li>
<li><a href="#all_emitter_emit_event_arg1_arg2">emitter.emit(event, [arg1], [arg2], [...])</a></li>
<li><a href="#all_class_method_eventemitter_listenercount_emitter_event">Class Method: EventEmitter.listenerCount(emitter, event)</a></li>
<li><a href="#all_event_newlistener">Event: 'newListener'</a></li>
<li><a href="#all_event_removelistener">Event: 'removeListener'</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_domain">Domain</a><ul>
<li><a href="#all_warning_don_t_ignore_errors">Warning: Don't Ignore Errors!</a></li>
<li><a href="#all_additions_to_error_objects">Additions to Error objects</a></li>
<li><a href="#all_implicit_binding">Implicit Binding</a></li>
<li><a href="#all_explicit_binding">Explicit Binding</a></li>
<li><a href="#all_domain_create">domain.create()</a></li>
<li><a href="#all_class_domain">Class: Domain</a><ul>
<li><a href="#all_domain_run_fn">domain.run(fn)</a></li>
<li><a href="#all_domain_members">domain.members</a></li>
<li><a href="#all_domain_add_emitter">domain.add(emitter)</a></li>
<li><a href="#all_domain_remove_emitter">domain.remove(emitter)</a></li>
<li><a href="#all_domain_bind_callback">domain.bind(callback)</a><ul>
<li><a href="#all_example">Example</a></li>
</ul>
</li>
<li><a href="#all_domain_intercept_callback">domain.intercept(callback)</a><ul>
<li><a href="#all_example_1">Example</a></li>
</ul>
</li>
<li><a href="#all_domain_enter">domain.enter()</a></li>
<li><a href="#all_domain_exit">domain.exit()</a></li>
<li><a href="#all_domain_dispose">domain.dispose()</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_buffer">Buffer</a><ul>
<li><a href="#all_class_buffer_1">Class: Buffer</a><ul>
<li><a href="#all_new_buffer_size">new Buffer(size)</a></li>
<li><a href="#all_new_buffer_array">new Buffer(array)</a></li>
<li><a href="#all_new_buffer_str_encoding">new Buffer(str, [encoding])</a></li>
<li><a href="#all_class_method_buffer_isencoding_encoding">Class Method: Buffer.isEncoding(encoding)</a></li>
<li><a href="#all_buf_write_string_offset_length_encoding">buf.write(string, [offset], [length], [encoding])</a></li>
<li><a href="#all_buf_tostring_encoding_start_end">buf.toString([encoding], [start], [end])</a></li>
<li><a href="#all_buf_tojson">buf.toJSON()</a></li>
<li><a href="#all_buf_index">buf[index]</a></li>
<li><a href="#all_class_method_buffer_isbuffer_obj">Class Method: Buffer.isBuffer(obj)</a></li>
<li><a href="#all_class_method_buffer_bytelength_string_encoding">Class Method: Buffer.byteLength(string, [encoding])</a></li>
<li><a href="#all_class_method_buffer_concat_list_totallength">Class Method: Buffer.concat(list, [totalLength])</a></li>
<li><a href="#all_buf_length">buf.length</a></li>
<li><a href="#all_buf_copy_targetbuffer_targetstart_sourcestart_sourceend">buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd])</a></li>
<li><a href="#all_buf_slice_start_end">buf.slice([start], [end])</a></li>
<li><a href="#all_buf_readuint8_offset_noassert">buf.readUInt8(offset, [noAssert])</a></li>
<li><a href="#all_buf_readuint16le_offset_noassert">buf.readUInt16LE(offset, [noAssert])</a></li>
<li><a href="#all_buf_readuint16be_offset_noassert">buf.readUInt16BE(offset, [noAssert])</a></li>
<li><a href="#all_buf_readuint32le_offset_noassert">buf.readUInt32LE(offset, [noAssert])</a></li>
<li><a href="#all_buf_readuint32be_offset_noassert">buf.readUInt32BE(offset, [noAssert])</a></li>
<li><a href="#all_buf_readint8_offset_noassert">buf.readInt8(offset, [noAssert])</a></li>
<li><a href="#all_buf_readint16le_offset_noassert">buf.readInt16LE(offset, [noAssert])</a></li>
<li><a href="#all_buf_readint16be_offset_noassert">buf.readInt16BE(offset, [noAssert])</a></li>
<li><a href="#all_buf_readint32le_offset_noassert">buf.readInt32LE(offset, [noAssert])</a></li>
<li><a href="#all_buf_readint32be_offset_noassert">buf.readInt32BE(offset, [noAssert])</a></li>
<li><a href="#all_buf_readfloatle_offset_noassert">buf.readFloatLE(offset, [noAssert])</a></li>
<li><a href="#all_buf_readfloatbe_offset_noassert">buf.readFloatBE(offset, [noAssert])</a></li>
<li><a href="#all_buf_readdoublele_offset_noassert">buf.readDoubleLE(offset, [noAssert])</a></li>
<li><a href="#all_buf_readdoublebe_offset_noassert">buf.readDoubleBE(offset, [noAssert])</a></li>
<li><a href="#all_buf_writeuint8_value_offset_noassert">buf.writeUInt8(value, offset, [noAssert])</a></li>
<li><a href="#all_buf_writeuint16le_value_offset_noassert">buf.writeUInt16LE(value, offset, [noAssert])</a></li>
<li><a href="#all_buf_writeuint16be_value_offset_noassert">buf.writeUInt16BE(value, offset, [noAssert])</a></li>
<li><a href="#all_buf_writeuint32le_value_offset_noassert">buf.writeUInt32LE(value, offset, [noAssert])</a></li>
<li><a href="#all_buf_writeuint32be_value_offset_noassert">buf.writeUInt32BE(value, offset, [noAssert])</a></li>
<li><a href="#all_buf_writeint8_value_offset_noassert">buf.writeInt8(value, offset, [noAssert])</a></li>
<li><a href="#all_buf_writeint16le_value_offset_noassert">buf.writeInt16LE(value, offset, [noAssert])</a></li>
<li><a href="#all_buf_writeint16be_value_offset_noassert">buf.writeInt16BE(value, offset, [noAssert])</a></li>
<li><a href="#all_buf_writeint32le_value_offset_noassert">buf.writeInt32LE(value, offset, [noAssert])</a></li>
<li><a href="#all_buf_writeint32be_value_offset_noassert">buf.writeInt32BE(value, offset, [noAssert])</a></li>
<li><a href="#all_buf_writefloatle_value_offset_noassert">buf.writeFloatLE(value, offset, [noAssert])</a></li>
<li><a href="#all_buf_writefloatbe_value_offset_noassert">buf.writeFloatBE(value, offset, [noAssert])</a></li>
<li><a href="#all_buf_writedoublele_value_offset_noassert">buf.writeDoubleLE(value, offset, [noAssert])</a></li>
<li><a href="#all_buf_writedoublebe_value_offset_noassert">buf.writeDoubleBE(value, offset, [noAssert])</a></li>
<li><a href="#all_buf_fill_value_offset_end">buf.fill(value, [offset], [end])</a></li>
</ul>
</li>
<li><a href="#all_buffer_inspect_max_bytes">buffer.INSPECT_MAX_BYTES</a></li>
<li><a href="#all_class_slowbuffer">Class: SlowBuffer</a></li>
</ul>
</li>
<li><a href="#all_stream">Stream</a><ul>
<li><a href="#all_api_for_stream_consumers">API for Stream Consumers</a><ul>
<li><a href="#all_class_stream_readable">Class: stream.Readable</a><ul>
<li><a href="#all_event_readable">Event: 'readable'</a></li>
<li><a href="#all_event_data">Event: 'data'</a></li>
<li><a href="#all_event_end">Event: 'end'</a></li>
<li><a href="#all_event_close">Event: 'close'</a></li>
<li><a href="#all_event_error">Event: 'error'</a></li>
<li><a href="#all_readable_read_size">readable.read([size])</a></li>
<li><a href="#all_readable_setencoding_encoding">readable.setEncoding(encoding)</a></li>
<li><a href="#all_readable_resume">readable.resume()</a></li>
<li><a href="#all_readable_pause">readable.pause()</a></li>
<li><a href="#all_readable_pipe_destination_options">readable.pipe(destination, [options])</a></li>
<li><a href="#all_readable_unpipe_destination">readable.unpipe([destination])</a></li>
<li><a href="#all_readable_unshift_chunk">readable.unshift(chunk)</a></li>
<li><a href="#all_readable_wrap_stream">readable.wrap(stream)</a></li>
</ul>
</li>
<li><a href="#all_class_stream_writable">Class: stream.Writable</a><ul>
<li><a href="#all_writable_write_chunk_encoding_callback">writable.write(chunk, [encoding], [callback])</a></li>
<li><a href="#all_event_drain">Event: 'drain'</a></li>
<li><a href="#all_writable_end_chunk_encoding_callback">writable.end([chunk], [encoding], [callback])</a></li>
<li><a href="#all_event_finish">Event: 'finish'</a></li>
<li><a href="#all_event_pipe">Event: 'pipe'</a></li>
<li><a href="#all_event_unpipe">Event: 'unpipe'</a></li>
<li><a href="#all_event_error_1">Event: 'error'</a></li>
</ul>
</li>
<li><a href="#all_class_stream_duplex">Class: stream.Duplex</a></li>
<li><a href="#all_class_stream_transform">Class: stream.Transform</a></li>
</ul>
</li>
<li><a href="#all_api_for_stream_implementors">API for Stream Implementors</a><ul>
<li><a href="#all_class_stream_readable_1">Class: stream.Readable</a><ul>
<li><a href="#all_example_a_counting_stream">Example: A Counting Stream</a></li>
<li><a href="#all_example_simpleprotocol_v1_sub_optimal">Example: SimpleProtocol v1 (Sub-optimal)</a></li>
<li><a href="#all_new_stream_readable_options">new stream.Readable([options])</a></li>
<li><a href="#all_readable_read_size_1">readable._read(size)</a></li>
<li><a href="#all_readable_push_chunk_encoding">readable.push(chunk, [encoding])</a></li>
</ul>
</li>
<li><a href="#all_class_stream_writable_1">Class: stream.Writable</a><ul>
<li><a href="#all_new_stream_writable_options">new stream.Writable([options])</a></li>
<li><a href="#all_writable_write_chunk_encoding_callback_1">writable._write(chunk, encoding, callback)</a></li>
</ul>
</li>
<li><a href="#all_class_stream_duplex_1">Class: stream.Duplex</a><ul>
<li><a href="#all_new_stream_duplex_options">new stream.Duplex(options)</a></li>
</ul>
</li>
<li><a href="#all_class_stream_transform_1">Class: stream.Transform</a><ul>
<li><a href="#all_new_stream_transform_options">new stream.Transform([options])</a></li>
<li><a href="#all_transform_transform_chunk_encoding_callback">transform._transform(chunk, encoding, callback)</a></li>
<li><a href="#all_transform_flush_callback">transform._flush(callback)</a></li>
<li><a href="#all_events_finish_and_end">Events: 'finish' and 'end'</a></li>
<li><a href="#all_example_simpleprotocol_parser_v2">Example: <code>SimpleProtocol</code> parser v2</a></li>
</ul>
</li>
<li><a href="#all_class_stream_passthrough">Class: stream.PassThrough</a></li>
</ul>
</li>
<li><a href="#all_streams_under_the_hood">Streams: Under the Hood</a><ul>
<li><a href="#all_buffering">Buffering</a></li>
<li><a href="#all_stream_read_0"><code>stream.read(0)</code></a></li>
<li><a href="#all_stream_push"><code>stream.push('')</code></a></li>
<li><a href="#all_compatibility_with_older_node_versions">Compatibility with Older Node Versions</a></li>
<li><a href="#all_object_mode">Object Mode</a></li>
<li><a href="#all_state_objects">State Objects</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_crypto">Crypto</a><ul>
<li><a href="#all_crypto_getciphers">crypto.getCiphers()</a></li>
<li><a href="#all_crypto_gethashes">crypto.getHashes()</a></li>
<li><a href="#all_crypto_createcredentials_details">crypto.createCredentials(details)</a></li>
<li><a href="#all_crypto_createhash_algorithm">crypto.createHash(algorithm)</a></li>
<li><a href="#all_class_hash">Class: Hash</a><ul>
<li><a href="#all_hash_update_data_input_encoding">hash.update(data, [input_encoding])</a></li>
<li><a href="#all_hash_digest_encoding">hash.digest([encoding])</a></li>
</ul>
</li>
<li><a href="#all_crypto_createhmac_algorithm_key">crypto.createHmac(algorithm, key)</a></li>
<li><a href="#all_class_hmac">Class: Hmac</a><ul>
<li><a href="#all_hmac_update_data">hmac.update(data)</a></li>
<li><a href="#all_hmac_digest_encoding">hmac.digest([encoding])</a></li>
</ul>
</li>
<li><a href="#all_crypto_createcipher_algorithm_password">crypto.createCipher(algorithm, password)</a></li>
<li><a href="#all_crypto_createcipheriv_algorithm_key_iv">crypto.createCipheriv(algorithm, key, iv)</a></li>
<li><a href="#all_class_cipher">Class: Cipher</a><ul>
<li><a href="#all_cipher_update_data_input_encoding_output_encoding">cipher.update(data, [input_encoding], [output_encoding])</a></li>
<li><a href="#all_cipher_final_output_encoding">cipher.final([output_encoding])</a></li>
<li><a href="#all_cipher_setautopadding_auto_padding_true">cipher.setAutoPadding(auto_padding=true)</a></li>
</ul>
</li>
<li><a href="#all_crypto_createdecipher_algorithm_password">crypto.createDecipher(algorithm, password)</a></li>
<li><a href="#all_crypto_createdecipheriv_algorithm_key_iv">crypto.createDecipheriv(algorithm, key, iv)</a></li>
<li><a href="#all_class_decipher">Class: Decipher</a><ul>
<li><a href="#all_decipher_update_data_input_encoding_output_encoding">decipher.update(data, [input_encoding], [output_encoding])</a></li>
<li><a href="#all_decipher_final_output_encoding">decipher.final([output_encoding])</a></li>
<li><a href="#all_decipher_setautopadding_auto_padding_true">decipher.setAutoPadding(auto_padding=true)</a></li>
</ul>
</li>
<li><a href="#all_crypto_createsign_algorithm">crypto.createSign(algorithm)</a></li>
<li><a href="#all_class_sign">Class: Sign</a><ul>
<li><a href="#all_sign_update_data">sign.update(data)</a></li>
<li><a href="#all_sign_sign_private_key_output_format">sign.sign(private_key, [output_format])</a></li>
</ul>
</li>
<li><a href="#all_crypto_createverify_algorithm">crypto.createVerify(algorithm)</a></li>
<li><a href="#all_class_verify">Class: Verify</a><ul>
<li><a href="#all_verifier_update_data">verifier.update(data)</a></li>
<li><a href="#all_verifier_verify_object_signature_signature_format">verifier.verify(object, signature, [signature_format])</a></li>
</ul>
</li>
<li><a href="#all_crypto_creatediffiehellman_prime_length">crypto.createDiffieHellman(prime_length)</a></li>
<li><a href="#all_crypto_creatediffiehellman_prime_encoding">crypto.createDiffieHellman(prime, [encoding])</a></li>
<li><a href="#all_class_diffiehellman">Class: DiffieHellman</a><ul>
<li><a href="#all_diffiehellman_generatekeys_encoding">diffieHellman.generateKeys([encoding])</a></li>
<li><a href="#all_diffiehellman_computesecret_other_public_key_input_encoding_output_encoding">diffieHellman.computeSecret(other_public_key, [input_encoding], [output_encoding])</a></li>
<li><a href="#all_diffiehellman_getprime_encoding">diffieHellman.getPrime([encoding])</a></li>
<li><a href="#all_diffiehellman_getgenerator_encoding">diffieHellman.getGenerator([encoding])</a></li>
<li><a href="#all_diffiehellman_getpublickey_encoding">diffieHellman.getPublicKey([encoding])</a></li>
<li><a href="#all_diffiehellman_getprivatekey_encoding">diffieHellman.getPrivateKey([encoding])</a></li>
<li><a href="#all_diffiehellman_setpublickey_public_key_encoding">diffieHellman.setPublicKey(public_key, [encoding])</a></li>
<li><a href="#all_diffiehellman_setprivatekey_private_key_encoding">diffieHellman.setPrivateKey(private_key, [encoding])</a></li>
</ul>
</li>
<li><a href="#all_crypto_getdiffiehellman_group_name">crypto.getDiffieHellman(group_name)</a></li>
<li><a href="#all_crypto_pbkdf2_password_salt_iterations_keylen_callback">crypto.pbkdf2(password, salt, iterations, keylen, callback)</a></li>
<li><a href="#all_crypto_pbkdf2sync_password_salt_iterations_keylen">crypto.pbkdf2Sync(password, salt, iterations, keylen)</a></li>
<li><a href="#all_crypto_randombytes_size_callback">crypto.randomBytes(size, [callback])</a></li>
<li><a href="#all_crypto_pseudorandombytes_size_callback">crypto.pseudoRandomBytes(size, [callback])</a></li>
<li><a href="#all_crypto_default_encoding">crypto.DEFAULT_ENCODING</a></li>
<li><a href="#all_recent_api_changes">Recent API Changes</a></li>
</ul>
</li>
<li><a href="#all_tls_ssl">TLS (SSL)</a><ul>
<li><a href="#all_client_initiated_renegotiation_attack_mitigation">Client-initiated renegotiation attack mitigation</a></li>
<li><a href="#all_npn_and_sni">NPN and SNI</a></li>
<li><a href="#all_tls_getciphers">tls.getCiphers()</a></li>
<li><a href="#all_tls_createserver_options_secureconnectionlistener">tls.createServer(options, [secureConnectionListener])</a></li>
<li><a href="#all_tls_slab_buffer_size">tls.SLAB_BUFFER_SIZE</a></li>
<li><a href="#all_tls_connect_options_callback">tls.connect(options, [callback])</a></li>
<li><a href="#all_tls_connect_port_host_options_callback">tls.connect(port, [host], [options], [callback])</a></li>
<li><a href="#all_tls_createsecurepair_credentials_isserver_requestcert_rejectunauthorized">tls.createSecurePair([credentials], [isServer], [requestCert], [rejectUnauthorized])</a></li>
<li><a href="#all_class_securepair">Class: SecurePair</a><ul>
<li><a href="#all_event_secure">Event: 'secure'</a></li>
</ul>
</li>
<li><a href="#all_class_tls_server">Class: tls.Server</a><ul>
<li><a href="#all_event_secureconnection">Event: 'secureConnection'</a></li>
<li><a href="#all_event_clienterror">Event: 'clientError'</a></li>
<li><a href="#all_event_newsession">Event: 'newSession'</a></li>
<li><a href="#all_event_resumesession">Event: 'resumeSession'</a></li>
<li><a href="#all_server_listen_port_host_callback">server.listen(port, [host], [callback])</a></li>
<li><a href="#all_server_close">server.close()</a></li>
<li><a href="#all_server_address">server.address()</a></li>
<li><a href="#all_server_addcontext_hostname_credentials">server.addContext(hostname, credentials)</a></li>
<li><a href="#all_server_maxconnections">server.maxConnections</a></li>
<li><a href="#all_server_connections">server.connections</a></li>
</ul>
</li>
<li><a href="#all_class_cryptostream">Class: CryptoStream</a><ul>
<li><a href="#all_cryptostream_byteswritten">cryptoStream.bytesWritten</a></li>
</ul>
</li>
<li><a href="#all_class_tls_cleartextstream">Class: tls.CleartextStream</a><ul>
<li><a href="#all_event_secureconnect">Event: 'secureConnect'</a></li>
<li><a href="#all_cleartextstream_authorized">cleartextStream.authorized</a></li>
<li><a href="#all_cleartextstream_authorizationerror">cleartextStream.authorizationError</a></li>
<li><a href="#all_cleartextstream_getpeercertificate">cleartextStream.getPeerCertificate()</a></li>
<li><a href="#all_cleartextstream_getcipher">cleartextStream.getCipher()</a></li>
<li><a href="#all_cleartextstream_address">cleartextStream.address()</a></li>
<li><a href="#all_cleartextstream_remoteaddress">cleartextStream.remoteAddress</a></li>
<li><a href="#all_cleartextstream_remoteport">cleartextStream.remotePort</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_stringdecoder">StringDecoder</a><ul>
<li><a href="#all_class_stringdecoder">Class: StringDecoder</a><ul>
<li><a href="#all_decoder_write_buffer">decoder.write(buffer)</a></li>
<li><a href="#all_decoder_end">decoder.end()</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_file_system">File System</a><ul>
<li><a href="#all_fs_rename_oldpath_newpath_callback">fs.rename(oldPath, newPath, callback)</a></li>
<li><a href="#all_fs_renamesync_oldpath_newpath">fs.renameSync(oldPath, newPath)</a></li>
<li><a href="#all_fs_ftruncate_fd_len_callback">fs.ftruncate(fd, len, callback)</a></li>
<li><a href="#all_fs_ftruncatesync_fd_len">fs.ftruncateSync(fd, len)</a></li>
<li><a href="#all_fs_truncate_path_len_callback">fs.truncate(path, len, callback)</a></li>
<li><a href="#all_fs_truncatesync_path_len">fs.truncateSync(path, len)</a></li>
<li><a href="#all_fs_chown_path_uid_gid_callback">fs.chown(path, uid, gid, callback)</a></li>
<li><a href="#all_fs_chownsync_path_uid_gid">fs.chownSync(path, uid, gid)</a></li>
<li><a href="#all_fs_fchown_fd_uid_gid_callback">fs.fchown(fd, uid, gid, callback)</a></li>
<li><a href="#all_fs_fchownsync_fd_uid_gid">fs.fchownSync(fd, uid, gid)</a></li>
<li><a href="#all_fs_lchown_path_uid_gid_callback">fs.lchown(path, uid, gid, callback)</a></li>
<li><a href="#all_fs_lchownsync_path_uid_gid">fs.lchownSync(path, uid, gid)</a></li>
<li><a href="#all_fs_chmod_path_mode_callback">fs.chmod(path, mode, callback)</a></li>
<li><a href="#all_fs_chmodsync_path_mode">fs.chmodSync(path, mode)</a></li>
<li><a href="#all_fs_fchmod_fd_mode_callback">fs.fchmod(fd, mode, callback)</a></li>
<li><a href="#all_fs_fchmodsync_fd_mode">fs.fchmodSync(fd, mode)</a></li>
<li><a href="#all_fs_lchmod_path_mode_callback">fs.lchmod(path, mode, callback)</a></li>
<li><a href="#all_fs_lchmodsync_path_mode">fs.lchmodSync(path, mode)</a></li>
<li><a href="#all_fs_stat_path_callback">fs.stat(path, callback)</a></li>
<li><a href="#all_fs_lstat_path_callback">fs.lstat(path, callback)</a></li>
<li><a href="#all_fs_fstat_fd_callback">fs.fstat(fd, callback)</a></li>
<li><a href="#all_fs_statsync_path">fs.statSync(path)</a></li>
<li><a href="#all_fs_lstatsync_path">fs.lstatSync(path)</a></li>
<li><a href="#all_fs_fstatsync_fd">fs.fstatSync(fd)</a></li>
<li><a href="#all_fs_link_srcpath_dstpath_callback">fs.link(srcpath, dstpath, callback)</a></li>
<li><a href="#all_fs_linksync_srcpath_dstpath">fs.linkSync(srcpath, dstpath)</a></li>
<li><a href="#all_fs_symlink_srcpath_dstpath_type_callback">fs.symlink(srcpath, dstpath, [type], callback)</a></li>
<li><a href="#all_fs_symlinksync_srcpath_dstpath_type">fs.symlinkSync(srcpath, dstpath, [type])</a></li>
<li><a href="#all_fs_readlink_path_callback">fs.readlink(path, callback)</a></li>
<li><a href="#all_fs_readlinksync_path">fs.readlinkSync(path)</a></li>
<li><a href="#all_fs_realpath_path_cache_callback">fs.realpath(path, [cache], callback)</a></li>
<li><a href="#all_fs_realpathsync_path_cache">fs.realpathSync(path, [cache])</a></li>
<li><a href="#all_fs_unlink_path_callback">fs.unlink(path, callback)</a></li>
<li><a href="#all_fs_unlinksync_path">fs.unlinkSync(path)</a></li>
<li><a href="#all_fs_rmdir_path_callback">fs.rmdir(path, callback)</a></li>
<li><a href="#all_fs_rmdirsync_path">fs.rmdirSync(path)</a></li>
<li><a href="#all_fs_mkdir_path_mode_callback">fs.mkdir(path, [mode], callback)</a></li>
<li><a href="#all_fs_mkdirsync_path_mode">fs.mkdirSync(path, [mode])</a></li>
<li><a href="#all_fs_readdir_path_callback">fs.readdir(path, callback)</a></li>
<li><a href="#all_fs_readdirsync_path">fs.readdirSync(path)</a></li>
<li><a href="#all_fs_close_fd_callback">fs.close(fd, callback)</a></li>
<li><a href="#all_fs_closesync_fd">fs.closeSync(fd)</a></li>
<li><a href="#all_fs_open_path_flags_mode_callback">fs.open(path, flags, [mode], callback)</a></li>
<li><a href="#all_fs_opensync_path_flags_mode">fs.openSync(path, flags, [mode])</a></li>
<li><a href="#all_fs_utimes_path_atime_mtime_callback">fs.utimes(path, atime, mtime, callback)</a></li>
<li><a href="#all_fs_utimessync_path_atime_mtime">fs.utimesSync(path, atime, mtime)</a></li>
<li><a href="#all_fs_futimes_fd_atime_mtime_callback">fs.futimes(fd, atime, mtime, callback)</a></li>
<li><a href="#all_fs_futimessync_fd_atime_mtime">fs.futimesSync(fd, atime, mtime)</a></li>
<li><a href="#all_fs_fsync_fd_callback">fs.fsync(fd, callback)</a></li>
<li><a href="#all_fs_fsyncsync_fd">fs.fsyncSync(fd)</a></li>
<li><a href="#all_fs_write_fd_buffer_offset_length_position_callback">fs.write(fd, buffer, offset, length, position, callback)</a></li>
<li><a href="#all_fs_writesync_fd_buffer_offset_length_position">fs.writeSync(fd, buffer, offset, length, position)</a></li>
<li><a href="#all_fs_read_fd_buffer_offset_length_position_callback">fs.read(fd, buffer, offset, length, position, callback)</a></li>
<li><a href="#all_fs_readsync_fd_buffer_offset_length_position">fs.readSync(fd, buffer, offset, length, position)</a></li>
<li><a href="#all_fs_readfile_filename_options_callback">fs.readFile(filename, [options], callback)</a></li>
<li><a href="#all_fs_readfilesync_filename_options">fs.readFileSync(filename, [options])</a></li>
<li><a href="#all_fs_writefile_filename_data_options_callback">fs.writeFile(filename, data, [options], callback)</a></li>
<li><a href="#all_fs_writefilesync_filename_data_options">fs.writeFileSync(filename, data, [options])</a></li>
<li><a href="#all_fs_appendfile_filename_data_options_callback">fs.appendFile(filename, data, [options], callback)</a></li>
<li><a href="#all_fs_appendfilesync_filename_data_options">fs.appendFileSync(filename, data, [options])</a></li>
<li><a href="#all_fs_watchfile_filename_options_listener">fs.watchFile(filename, [options], listener)</a></li>
<li><a href="#all_fs_unwatchfile_filename_listener">fs.unwatchFile(filename, [listener])</a></li>
<li><a href="#all_fs_watch_filename_options_listener">fs.watch(filename, [options], [listener])</a><ul>
<li><a href="#all_caveats">Caveats</a><ul>
<li><a href="#all_availability">Availability</a></li>
<li><a href="#all_filename_argument">Filename Argument</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_fs_exists_path_callback">fs.exists(path, callback)</a></li>
<li><a href="#all_fs_existssync_path">fs.existsSync(path)</a></li>
<li><a href="#all_class_fs_stats">Class: fs.Stats</a></li>
<li><a href="#all_fs_createreadstream_path_options">fs.createReadStream(path, [options])</a></li>
<li><a href="#all_class_fs_readstream">Class: fs.ReadStream</a><ul>
<li><a href="#all_event_open">Event: 'open'</a></li>
</ul>
</li>
<li><a href="#all_fs_createwritestream_path_options">fs.createWriteStream(path, [options])</a></li>
<li><a href="#all_class_fs_writestream">Class: fs.WriteStream</a><ul>
<li><a href="#all_event_open_1">Event: 'open'</a></li>
<li><a href="#all_file_byteswritten">file.bytesWritten</a></li>
</ul>
</li>
<li><a href="#all_class_fs_fswatcher">Class: fs.FSWatcher</a><ul>
<li><a href="#all_watcher_close">watcher.close()</a></li>
<li><a href="#all_event_change">Event: 'change'</a></li>
<li><a href="#all_event_error_2">Event: 'error'</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_path">Path</a><ul>
<li><a href="#all_path_normalize_p">path.normalize(p)</a></li>
<li><a href="#all_path_join_path1_path2">path.join([path1], [path2], [...])</a></li>
<li><a href="#all_path_resolve_from_to">path.resolve([from ...], to)</a></li>
<li><a href="#all_path_relative_from_to">path.relative(from, to)</a></li>
<li><a href="#all_path_dirname_p">path.dirname(p)</a></li>
<li><a href="#all_path_basename_p_ext">path.basename(p, [ext])</a></li>
<li><a href="#all_path_extname_p">path.extname(p)</a></li>
<li><a href="#all_path_sep">path.sep</a></li>
<li><a href="#all_path_delimiter">path.delimiter</a></li>
</ul>
</li>
<li><a href="#all_net">net</a><ul>
<li><a href="#all_net_createserver_options_connectionlistener">net.createServer([options], [connectionListener])</a></li>
<li><a href="#all_net_connect_options_connectionlistener">net.connect(options, [connectionListener])</a></li>
<li><a href="#all_net_createconnection_options_connectionlistener">net.createConnection(options, [connectionListener])</a></li>
<li><a href="#all_net_connect_port_host_connectlistener">net.connect(port, [host], [connectListener])</a></li>
<li><a href="#all_net_createconnection_port_host_connectlistener">net.createConnection(port, [host], [connectListener])</a></li>
<li><a href="#all_net_connect_path_connectlistener">net.connect(path, [connectListener])</a></li>
<li><a href="#all_net_createconnection_path_connectlistener">net.createConnection(path, [connectListener])</a></li>
<li><a href="#all_class_net_server">Class: net.Server</a><ul>
<li><a href="#all_server_listen_port_host_backlog_callback">server.listen(port, [host], [backlog], [callback])</a></li>
<li><a href="#all_server_listen_path_callback">server.listen(path, [callback])</a></li>
<li><a href="#all_server_listen_handle_callback">server.listen(handle, [callback])</a></li>
<li><a href="#all_server_close_callback">server.close([callback])</a></li>
<li><a href="#all_server_address_1">server.address()</a></li>
<li><a href="#all_server_unref">server.unref()</a></li>
<li><a href="#all_server_ref">server.ref()</a></li>
<li><a href="#all_server_maxconnections_1">server.maxConnections</a></li>
<li><a href="#all_server_connections_1">server.connections</a></li>
<li><a href="#all_server_getconnections_callback">server.getConnections(callback)</a></li>
<li><a href="#all_event_listening">Event: 'listening'</a></li>
<li><a href="#all_event_connection">Event: 'connection'</a></li>
<li><a href="#all_event_close_1">Event: 'close'</a></li>
<li><a href="#all_event_error_3">Event: 'error'</a></li>
</ul>
</li>
<li><a href="#all_class_net_socket">Class: net.Socket</a><ul>
<li><a href="#all_new_net_socket_options">new net.Socket([options])</a></li>
<li><a href="#all_socket_connect_port_host_connectlistener">socket.connect(port, [host], [connectListener])</a></li>
<li><a href="#all_socket_connect_path_connectlistener">socket.connect(path, [connectListener])</a></li>
<li><a href="#all_socket_buffersize">socket.bufferSize</a></li>
<li><a href="#all_socket_setencoding_encoding">socket.setEncoding([encoding])</a></li>
<li><a href="#all_socket_write_data_encoding_callback">socket.write(data, [encoding], [callback])</a></li>
<li><a href="#all_socket_end_data_encoding">socket.end([data], [encoding])</a></li>
<li><a href="#all_socket_destroy">socket.destroy()</a></li>
<li><a href="#all_socket_pause">socket.pause()</a></li>
<li><a href="#all_socket_resume">socket.resume()</a></li>
<li><a href="#all_socket_settimeout_timeout_callback">socket.setTimeout(timeout, [callback])</a></li>
<li><a href="#all_socket_setnodelay_nodelay">socket.setNoDelay([noDelay])</a></li>
<li><a href="#all_socket_setkeepalive_enable_initialdelay">socket.setKeepAlive([enable], [initialDelay])</a></li>
<li><a href="#all_socket_address">socket.address()</a></li>
<li><a href="#all_socket_unref">socket.unref()</a></li>
<li><a href="#all_socket_ref">socket.ref()</a></li>
<li><a href="#all_socket_remoteaddress">socket.remoteAddress</a></li>
<li><a href="#all_socket_remoteport">socket.remotePort</a></li>
<li><a href="#all_socket_localaddress">socket.localAddress</a></li>
<li><a href="#all_socket_localport">socket.localPort</a></li>
<li><a href="#all_socket_bytesread">socket.bytesRead</a></li>
<li><a href="#all_socket_byteswritten">socket.bytesWritten</a></li>
<li><a href="#all_event_connect">Event: 'connect'</a></li>
<li><a href="#all_event_data_1">Event: 'data'</a></li>
<li><a href="#all_event_end_1">Event: 'end'</a></li>
<li><a href="#all_event_timeout">Event: 'timeout'</a></li>
<li><a href="#all_event_drain_1">Event: 'drain'</a></li>
<li><a href="#all_event_error_4">Event: 'error'</a></li>
<li><a href="#all_event_close_2">Event: 'close'</a></li>
</ul>
</li>
<li><a href="#all_net_isip_input">net.isIP(input)</a></li>
<li><a href="#all_net_isipv4_input">net.isIPv4(input)</a></li>
<li><a href="#all_net_isipv6_input">net.isIPv6(input)</a></li>
</ul>
</li>
<li><a href="#all_udp_datagram_sockets">UDP / Datagram Sockets</a><ul>
<li><a href="#all_dgram_createsocket_type_callback">dgram.createSocket(type, [callback])</a></li>
<li><a href="#all_class_dgram_socket">Class: dgram.Socket</a><ul>
<li><a href="#all_event_message">Event: 'message'</a></li>
<li><a href="#all_event_listening_1">Event: 'listening'</a></li>
<li><a href="#all_event_close_3">Event: 'close'</a></li>
<li><a href="#all_event_error_5">Event: 'error'</a></li>
<li><a href="#all_socket_send_buf_offset_length_port_address_callback">socket.send(buf, offset, length, port, address, [callback])</a></li>
<li><a href="#all_socket_bind_port_address_callback">socket.bind(port, [address], [callback])</a></li>
<li><a href="#all_socket_close">socket.close()</a></li>
<li><a href="#all_socket_address_1">socket.address()</a></li>
<li><a href="#all_socket_setbroadcast_flag">socket.setBroadcast(flag)</a></li>
<li><a href="#all_socket_setttl_ttl">socket.setTTL(ttl)</a></li>
<li><a href="#all_socket_setmulticastttl_ttl">socket.setMulticastTTL(ttl)</a></li>
<li><a href="#all_socket_setmulticastloopback_flag">socket.setMulticastLoopback(flag)</a></li>
<li><a href="#all_socket_addmembership_multicastaddress_multicastinterface">socket.addMembership(multicastAddress, [multicastInterface])</a></li>
<li><a href="#all_socket_dropmembership_multicastaddress_multicastinterface">socket.dropMembership(multicastAddress, [multicastInterface])</a></li>
<li><a href="#all_socket_unref_1">socket.unref()</a></li>
<li><a href="#all_socket_ref_1">socket.ref()</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_dns">DNS</a><ul>
<li><a href="#all_dns_lookup_domain_family_callback">dns.lookup(domain, [family], callback)</a></li>
<li><a href="#all_dns_resolve_domain_rrtype_callback">dns.resolve(domain, [rrtype], callback)</a></li>
<li><a href="#all_dns_resolve4_domain_callback">dns.resolve4(domain, callback)</a></li>
<li><a href="#all_dns_resolve6_domain_callback">dns.resolve6(domain, callback)</a></li>
<li><a href="#all_dns_resolvemx_domain_callback">dns.resolveMx(domain, callback)</a></li>
<li><a href="#all_dns_resolvetxt_domain_callback">dns.resolveTxt(domain, callback)</a></li>
<li><a href="#all_dns_resolvesrv_domain_callback">dns.resolveSrv(domain, callback)</a></li>
<li><a href="#all_dns_resolvens_domain_callback">dns.resolveNs(domain, callback)</a></li>
<li><a href="#all_dns_resolvecname_domain_callback">dns.resolveCname(domain, callback)</a></li>
<li><a href="#all_dns_reverse_ip_callback">dns.reverse(ip, callback)</a></li>
<li><a href="#all_error_codes">Error codes</a></li>
</ul>
</li>
<li><a href="#all_http">HTTP</a><ul>
<li><a href="#all_http_status_codes">http.STATUS_CODES</a></li>
<li><a href="#all_http_createserver_requestlistener">http.createServer([requestListener])</a></li>
<li><a href="#all_http_createclient_port_host">http.createClient([port], [host])</a></li>
<li><a href="#all_class_http_server">Class: http.Server</a><ul>
<li><a href="#all_event_request">Event: 'request'</a></li>
<li><a href="#all_event_connection_1">Event: 'connection'</a></li>
<li><a href="#all_event_close_4">Event: 'close'</a></li>
<li><a href="#all_event_checkcontinue">Event: 'checkContinue'</a></li>
<li><a href="#all_event_connect_1">Event: 'connect'</a></li>
<li><a href="#all_event_upgrade">Event: 'upgrade'</a></li>
<li><a href="#all_event_clienterror_1">Event: 'clientError'</a></li>
<li><a href="#all_server_listen_port_hostname_backlog_callback">server.listen(port, [hostname], [backlog], [callback])</a></li>
<li><a href="#all_server_listen_path_callback_1">server.listen(path, [callback])</a></li>
<li><a href="#all_server_listen_handle_callback_1">server.listen(handle, [callback])</a></li>
<li><a href="#all_server_close_callback_1">server.close([callback])</a></li>
<li><a href="#all_server_maxheaderscount">server.maxHeadersCount</a></li>
<li><a href="#all_server_settimeout_msecs_callback">server.setTimeout(msecs, callback)</a></li>
<li><a href="#all_server_timeout">server.timeout</a></li>
</ul>
</li>
<li><a href="#all_class_http_serverresponse">Class: http.ServerResponse</a><ul>
<li><a href="#all_event_close_5">Event: 'close'</a></li>
<li><a href="#all_event_finish_1">Event: 'finish'</a></li>
<li><a href="#all_response_writecontinue">response.writeContinue()</a></li>
<li><a href="#all_response_writehead_statuscode_reasonphrase_headers">response.writeHead(statusCode, [reasonPhrase], [headers])</a></li>
<li><a href="#all_response_settimeout_msecs_callback">response.setTimeout(msecs, callback)</a></li>
<li><a href="#all_response_statuscode">response.statusCode</a></li>
<li><a href="#all_response_setheader_name_value">response.setHeader(name, value)</a></li>
<li><a href="#all_response_headerssent">response.headersSent</a></li>
<li><a href="#all_response_senddate">response.sendDate</a></li>
<li><a href="#all_response_getheader_name">response.getHeader(name)</a></li>
<li><a href="#all_response_removeheader_name">response.removeHeader(name)</a></li>
<li><a href="#all_response_write_chunk_encoding">response.write(chunk, [encoding])</a></li>
<li><a href="#all_response_addtrailers_headers">response.addTrailers(headers)</a></li>
<li><a href="#all_response_end_data_encoding">response.end([data], [encoding])</a></li>
</ul>
</li>
<li><a href="#all_http_request_options_callback">http.request(options, [callback])</a></li>
<li><a href="#all_http_get_options_callback">http.get(options, [callback])</a></li>
<li><a href="#all_class_http_agent">Class: http.Agent</a><ul>
<li><a href="#all_agent_maxsockets">agent.maxSockets</a></li>
<li><a href="#all_agent_sockets">agent.sockets</a></li>
<li><a href="#all_agent_requests">agent.requests</a></li>
</ul>
</li>
<li><a href="#all_http_globalagent">http.globalAgent</a></li>
<li><a href="#all_class_http_clientrequest">Class: http.ClientRequest</a><ul>
<li><a href="#all_event_response">Event 'response'</a></li>
<li><a href="#all_event_socket">Event: 'socket'</a></li>
<li><a href="#all_event_connect_2">Event: 'connect'</a></li>
<li><a href="#all_event_upgrade_1">Event: 'upgrade'</a></li>
<li><a href="#all_event_continue">Event: 'continue'</a></li>
<li><a href="#all_request_write_chunk_encoding">request.write(chunk, [encoding])</a></li>
<li><a href="#all_request_end_data_encoding">request.end([data], [encoding])</a></li>
<li><a href="#all_request_abort">request.abort()</a></li>
<li><a href="#all_request_settimeout_timeout_callback">request.setTimeout(timeout, [callback])</a></li>
<li><a href="#all_request_setnodelay_nodelay">request.setNoDelay([noDelay])</a></li>
<li><a href="#all_request_setsocketkeepalive_enable_initialdelay">request.setSocketKeepAlive([enable], [initialDelay])</a></li>
</ul>
</li>
<li><a href="#all_http_incomingmessage">http.IncomingMessage</a><ul>
<li><a href="#all_event_close_6">Event: 'close'</a></li>
<li><a href="#all_message_httpversion">message.httpVersion</a></li>
<li><a href="#all_message_headers">message.headers</a></li>
<li><a href="#all_message_trailers">message.trailers</a></li>
<li><a href="#all_message_settimeout_msecs_callback">message.setTimeout(msecs, callback)</a></li>
<li><a href="#all_message_method">message.method</a></li>
<li><a href="#all_message_url">message.url</a></li>
<li><a href="#all_message_statuscode">message.statusCode</a></li>
<li><a href="#all_message_socket">message.socket</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_https">HTTPS</a><ul>
<li><a href="#all_class_https_server">Class: https.Server</a></li>
<li><a href="#all_https_createserver_options_requestlistener">https.createServer(options, [requestListener])</a><ul>
<li><a href="#all_server_listen_port_host_backlog_callback_1">server.listen(port, [host], [backlog], [callback])</a></li>
<li><a href="#all_server_listen_path_callback_2">server.listen(path, [callback])</a></li>
<li><a href="#all_server_listen_handle_callback_2">server.listen(handle, [callback])</a></li>
<li><a href="#all_server_close_callback_2">server.close([callback])</a></li>
</ul>
</li>
<li><a href="#all_https_request_options_callback">https.request(options, callback)</a></li>
<li><a href="#all_https_get_options_callback">https.get(options, callback)</a></li>
<li><a href="#all_class_https_agent">Class: https.Agent</a></li>
<li><a href="#all_https_globalagent">https.globalAgent</a></li>
</ul>
</li>
<li><a href="#all_url">URL</a><ul>
<li><a href="#all_url_parse_urlstr_parsequerystring_slashesdenotehost">url.parse(urlStr, [parseQueryString], [slashesDenoteHost])</a></li>
<li><a href="#all_url_format_urlobj">url.format(urlObj)</a></li>
<li><a href="#all_url_resolve_from_to">url.resolve(from, to)</a></li>
</ul>
</li>
<li><a href="#all_query_string">Query String</a><ul>
<li><a href="#all_querystring_stringify_obj_sep_eq">querystring.stringify(obj, [sep], [eq])</a></li>
<li><a href="#all_querystring_parse_str_sep_eq_options">querystring.parse(str, [sep], [eq], [options])</a></li>
<li><a href="#all_querystring_escape">querystring.escape</a></li>
<li><a href="#all_querystring_unescape">querystring.unescape</a></li>
</ul>
</li>
<li><a href="#all_punycode">punycode</a><ul>
<li><a href="#all_punycode_decode_string">punycode.decode(string)</a></li>
<li><a href="#all_punycode_encode_string">punycode.encode(string)</a></li>
<li><a href="#all_punycode_tounicode_domain">punycode.toUnicode(domain)</a></li>
<li><a href="#all_punycode_toascii_domain">punycode.toASCII(domain)</a></li>
<li><a href="#all_punycode_ucs2">punycode.ucs2</a><ul>
<li><a href="#all_punycode_ucs2_decode_string">punycode.ucs2.decode(string)</a></li>
<li><a href="#all_punycode_ucs2_encode_codepoints">punycode.ucs2.encode(codePoints)</a></li>
</ul>
</li>
<li><a href="#all_punycode_version">punycode.version</a></li>
</ul>
</li>
<li><a href="#all_readline">Readline</a><ul>
<li><a href="#all_readline_createinterface_options">readline.createInterface(options)</a></li>
<li><a href="#all_class_interface">Class: Interface</a><ul>
<li><a href="#all_rl_setprompt_prompt_length">rl.setPrompt(prompt, length)</a></li>
<li><a href="#all_rl_prompt_preservecursor">rl.prompt([preserveCursor])</a></li>
<li><a href="#all_rl_question_query_callback">rl.question(query, callback)</a></li>
<li><a href="#all_rl_pause">rl.pause()</a></li>
<li><a href="#all_rl_resume">rl.resume()</a></li>
<li><a href="#all_rl_close">rl.close()</a></li>
<li><a href="#all_rl_write_data_key">rl.write(data, [key])</a></li>
</ul>
</li>
<li><a href="#all_events_1">Events</a><ul>
<li><a href="#all_event_line">Event: 'line'</a></li>
<li><a href="#all_event_pause">Event: 'pause'</a></li>
<li><a href="#all_event_resume">Event: 'resume'</a></li>
<li><a href="#all_event_close_7">Event: 'close'</a></li>
<li><a href="#all_event_sigint">Event: 'SIGINT'</a></li>
<li><a href="#all_event_sigtstp">Event: 'SIGTSTP'</a></li>
<li><a href="#all_event_sigcont">Event: 'SIGCONT'</a></li>
</ul>
</li>
<li><a href="#all_example_tiny_cli">Example: Tiny CLI</a></li>
<li><a href="#all_readline_cursorto_stream_x_y">readline.cursorTo(stream, x, y)</a></li>
<li><a href="#all_readline_movecursor_stream_dx_dy">readline.moveCursor(stream, dx, dy)</a></li>
<li><a href="#all_readline_clearline_stream_dir">readline.clearLine(stream, dir)</a></li>
<li><a href="#all_readline_clearscreendown_stream">readline.clearScreenDown(stream)</a></li>
</ul>
</li>
<li><a href="#all_repl">REPL</a><ul>
<li><a href="#all_repl_start_options">repl.start(options)</a><ul>
<li><a href="#all_event_exit_1">Event: 'exit'</a></li>
</ul>
</li>
<li><a href="#all_repl_features">REPL Features</a></li>
</ul>
</li>
<li><a href="#all_executing_javascript">Executing JavaScript</a><ul>
<li><a href="#all_caveats_1">Caveats</a><ul>
<li><a href="#all_sandboxes">Sandboxes</a></li>
<li><a href="#all_globals">Globals</a></li>
</ul>
</li>
<li><a href="#all_vm_runinthiscontext_code_filename">vm.runInThisContext(code, [filename])</a></li>
<li><a href="#all_vm_runinnewcontext_code_sandbox_filename">vm.runInNewContext(code, [sandbox], [filename])</a></li>
<li><a href="#all_vm_runincontext_code_context_filename">vm.runInContext(code, context, [filename])</a></li>
<li><a href="#all_vm_createcontext_initsandbox">vm.createContext([initSandbox])</a></li>
<li><a href="#all_vm_createscript_code_filename">vm.createScript(code, [filename])</a></li>
<li><a href="#all_class_script">Class: Script</a><ul>
<li><a href="#all_script_runinthiscontext">script.runInThisContext()</a></li>
<li><a href="#all_script_runinnewcontext_sandbox">script.runInNewContext([sandbox])</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_child_process">Child Process</a><ul>
<li><a href="#all_class_childprocess">Class: ChildProcess</a><ul>
<li><a href="#all_event_error_6">Event: 'error'</a></li>
<li><a href="#all_event_exit_2">Event: 'exit'</a></li>
<li><a href="#all_event_close_8">Event: 'close'</a></li>
<li><a href="#all_event_disconnect">Event: 'disconnect'</a></li>
<li><a href="#all_event_message_1">Event: 'message'</a></li>
<li><a href="#all_child_stdin">child.stdin</a></li>
<li><a href="#all_child_stdout">child.stdout</a></li>
<li><a href="#all_child_stderr">child.stderr</a></li>
<li><a href="#all_child_pid">child.pid</a></li>
<li><a href="#all_child_connected">child.connected</a></li>
<li><a href="#all_child_kill_signal">child.kill([signal])</a></li>
<li><a href="#all_child_send_message_sendhandle">child.send(message, [sendHandle])</a><ul>
<li><a href="#all_example_sending_server_object">Example: sending server object</a></li>
<li><a href="#all_example_sending_socket_object">Example: sending socket object</a></li>
</ul>
</li>
<li><a href="#all_child_disconnect">child.disconnect()</a></li>
</ul>
</li>
<li><a href="#all_child_process_spawn_command_args_options">child_process.spawn(command, [args], [options])</a></li>
<li><a href="#all_child_process_exec_command_options_callback">child_process.exec(command, [options], callback)</a></li>
<li><a href="#all_child_process_execfile_file_args_options_callback">child_process.execFile(file, [args], [options], [callback])</a></li>
<li><a href="#all_child_process_fork_modulepath_args_options">child_process.fork(modulePath, [args], [options])</a></li>
</ul>
</li>
<li><a href="#all_assert">Assert</a><ul>
<li><a href="#all_assert_fail_actual_expected_message_operator">assert.fail(actual, expected, message, operator)</a></li>
<li><a href="#all_assert_value_message_assert_ok_value_message">assert(value, message), assert.ok(value, [message])</a></li>
<li><a href="#all_assert_equal_actual_expected_message">assert.equal(actual, expected, [message])</a></li>
<li><a href="#all_assert_notequal_actual_expected_message">assert.notEqual(actual, expected, [message])</a></li>
<li><a href="#all_assert_deepequal_actual_expected_message">assert.deepEqual(actual, expected, [message])</a></li>
<li><a href="#all_assert_notdeepequal_actual_expected_message">assert.notDeepEqual(actual, expected, [message])</a></li>
<li><a href="#all_assert_strictequal_actual_expected_message">assert.strictEqual(actual, expected, [message])</a></li>
<li><a href="#all_assert_notstrictequal_actual_expected_message">assert.notStrictEqual(actual, expected, [message])</a></li>
<li><a href="#all_assert_throws_block_error_message">assert.throws(block, [error], [message])</a></li>
<li><a href="#all_assert_doesnotthrow_block_message">assert.doesNotThrow(block, [message])</a></li>
<li><a href="#all_assert_iferror_value">assert.ifError(value)</a></li>
</ul>
</li>
<li><a href="#all_tty">TTY</a><ul>
<li><a href="#all_tty_isatty_fd">tty.isatty(fd)</a></li>
<li><a href="#all_tty_setrawmode_mode">tty.setRawMode(mode)</a></li>
<li><a href="#all_class_readstream">Class: ReadStream</a><ul>
<li><a href="#all_rs_israw">rs.isRaw</a></li>
<li><a href="#all_rs_setrawmode_mode">rs.setRawMode(mode)</a></li>
</ul>
</li>
<li><a href="#all_class_writestream">Class: WriteStream</a><ul>
<li><a href="#all_ws_columns">ws.columns</a></li>
<li><a href="#all_ws_rows">ws.rows</a></li>
<li><a href="#all_event_resize">Event: 'resize'</a></li>
</ul>
</li>
</ul>
</li>
<li><a href="#all_zlib">Zlib</a><ul>
<li><a href="#all_examples">Examples</a></li>
<li><a href="#all_zlib_creategzip_options">zlib.createGzip([options])</a></li>
<li><a href="#all_zlib_creategunzip_options">zlib.createGunzip([options])</a></li>
<li><a href="#all_zlib_createdeflate_options">zlib.createDeflate([options])</a></li>
<li><a href="#all_zlib_createinflate_options">zlib.createInflate([options])</a></li>
<li><a href="#all_zlib_createdeflateraw_options">zlib.createDeflateRaw([options])</a></li>
<li><a href="#all_zlib_createinflateraw_options">zlib.createInflateRaw([options])</a></li>
<li><a href="#all_zlib_createunzip_options">zlib.createUnzip([options])</a></li>
<li><a href="#all_class_zlib_zlib">Class: zlib.Zlib</a><ul>
<li><a href="#all_zlib_flush_callback">zlib.flush(callback)</a></li>
<li><a href="#all_zlib_reset">zlib.reset()</a></li>
</ul>
</li>
<li><a href="#all_class_zlib_gzip">Class: zlib.Gzip</a></li>
<li><a href="#all_class_zlib_gunzip">Class: zlib.Gunzip</a></li>
<li><a href="#all_class_zlib_deflate">Class: zlib.Deflate</a></li>
<li><a href="#all_class_zlib_inflate">Class: zlib.Inflate</a></li>
<li><a href="#all_class_zlib_deflateraw">Class: zlib.DeflateRaw</a></li>
<li><a href="#all_class_zlib_inflateraw">Class: zlib.InflateRaw</a></li>
<li><a href="#all_class_zlib_unzip">Class: zlib.Unzip</a></li>
<li><a href="#all_convenience_methods">Convenience Methods</a></li>
<li><a href="#all_zlib_deflate_buf_callback">zlib.deflate(buf, callback)</a></li>
<li><a href="#all_zlib_deflateraw_buf_callback">zlib.deflateRaw(buf, callback)</a></li>
<li><a href="#all_zlib_gzip_buf_callback">zlib.gzip(buf, callback)</a></li>
<li><a href="#all_zlib_gunzip_buf_callback">zlib.gunzip(buf, callback)</a></li>
<li><a href="#all_zlib_inflate_buf_callback">zlib.inflate(buf, callback)</a></li>
<li><a href="#all_zlib_inflateraw_buf_callback">zlib.inflateRaw(buf, callback)</a></li>
<li><a href="#all_zlib_unzip_buf_callback">zlib.unzip(buf, callback)</a></li>
<li><a href="#all_options">Options</a></li>
<li><a href="#all_memory_usage_tuning">Memory Usage Tuning</a></li>
<li><a href="#all_constants">Constants</a></li>
</ul>
</li>
<li><a href="#all_os">os</a><ul>
<li><a href="#all_os_tmpdir">os.tmpdir()</a></li>
<li><a href="#all_os_endianness">os.endianness()</a></li>
<li><a href="#all_os_hostname">os.hostname()</a></li>
<li><a href="#all_os_type">os.type()</a></li>
<li><a href="#all_os_platform">os.platform()</a></li>
<li><a href="#all_os_arch">os.arch()</a></li>
<li><a href="#all_os_release">os.release()</a></li>
<li><a href="#all_os_uptime">os.uptime()</a></li>
<li><a href="#all_os_loadavg">os.loadavg()</a></li>
<li><a href="#all_os_totalmem">os.totalmem()</a></li>
<li><a href="#all_os_freemem">os.freemem()</a></li>
<li><a href="#all_os_cpus">os.cpus()</a></li>
<li><a href="#all_os_networkinterfaces">os.networkInterfaces()</a></li>
<li><a href="#all_os_eol">os.EOL</a></li>
</ul>
</li>
<li><a href="#all_debugger">Debugger</a><ul>
<li><a href="#all_watchers">Watchers</a></li>
<li><a href="#all_commands_reference">Commands reference</a><ul>
<li><a href="#all_stepping">Stepping</a></li>
<li><a href="#all_breakpoints">Breakpoints</a></li>
<li><a href="#all_info">Info</a></li>
<li><a href="#all_execution_control">Execution control</a></li>
<li><a href="#all_various">Various</a></li>
</ul>
</li>
<li><a href="#all_advanced_usage">Advanced Usage</a></li>
</ul>
</li>
<li><a href="#all_cluster">Cluster</a><ul>
<li><a href="#all_how_it_works">How It Works</a></li>
<li><a href="#all_cluster_settings">cluster.settings</a></li>
<li><a href="#all_cluster_ismaster">cluster.isMaster</a></li>
<li><a href="#all_cluster_isworker">cluster.isWorker</a></li>
<li><a href="#all_event_fork">Event: 'fork'</a></li>
<li><a href="#all_event_online">Event: 'online'</a></li>
<li><a href="#all_event_listening_2">Event: 'listening'</a></li>
<li><a href="#all_event_disconnect_1">Event: 'disconnect'</a></li>
<li><a href="#all_event_exit_3">Event: 'exit'</a></li>
<li><a href="#all_event_setup">Event: 'setup'</a></li>
<li><a href="#all_cluster_setupmaster_settings">cluster.setupMaster([settings])</a></li>
<li><a href="#all_cluster_fork_env">cluster.fork([env])</a></li>
<li><a href="#all_cluster_disconnect_callback">cluster.disconnect([callback])</a></li>
<li><a href="#all_cluster_worker">cluster.worker</a></li>
<li><a href="#all_cluster_workers">cluster.workers</a></li>
<li><a href="#all_class_worker">Class: Worker</a><ul>
<li><a href="#all_worker_id">worker.id</a></li>
<li><a href="#all_worker_process">worker.process</a></li>
<li><a href="#all_worker_suicide">worker.suicide</a></li>
<li><a href="#all_worker_send_message_sendhandle">worker.send(message, [sendHandle])</a></li>
<li><a href="#all_worker_kill_signal_sigterm">worker.kill([signal='SIGTERM'])</a></li>
<li><a href="#all_worker_disconnect">worker.disconnect()</a></li>
<li><a href="#all_event_message_2">Event: 'message'</a></li>
<li><a href="#all_event_online_1">Event: 'online'</a></li>
<li><a href="#all_event_listening_3">Event: 'listening'</a></li>
<li><a href="#all_event_disconnect_2">Event: 'disconnect'</a></li>
<li><a href="#all_event_exit_4">Event: 'exit'</a></li>
<li><a href="#all_event_error_7">Event: 'error'</a></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div id="apicontent">
<h1>About this Documentation<span><a class="mark" href="#all_about_this_documentation" id="all_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>.markdown</code> file in the <code>doc/api/</code> folder in node'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>
<h2>Stability Index<span><a class="mark" href="#all_stability_index" id="all_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_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_1">Stability: 1 - Experimental
This feature was introduced recently, and may change
or be removed in future versions. Please try it out and provide feedback.
If it addresses a use-case that is important to you, tell the node core team.</pre><pre class="api_stability_2">Stability: 2 - Unstable
The API is in the process of settling, but has not yet had
sufficient real-world testing to be considered stable. Backwards-compatibility
will be maintained if reasonable.</pre><pre class="api_stability_3">Stability: 3 - Stable
The API has proven satisfactory, but cleanup in the underlying
code may cause minor changes. Backwards-compatibility is guaranteed.</pre><pre class="api_stability_4">Stability: 4 - API Frozen
This API has been tested extensively in production and is
unlikely to ever have to change.</pre><pre class="api_stability_5">Stability: 5 - Locked
Unless serious bugs are found, this code will not ever
change. Please do not suggest changes in this area; they will be refused.</pre><h2>JSON Output<span><a class="mark" href="#all_json_output" id="all_json_output">#</a></span></h2>
<pre class="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 is new as of node v0.6.12. It is experimental.
</p>
<h1>Synopsis<span><a class="mark" href="#all_synopsis" id="all_synopsis">#</a></span></h1>
<!--type=misc-->
<p>An example of a <a href="http.html">web server</a> written with Node which responds with 'Hello
World':
</p>
<pre><code>var http = require('http');
http.createServer(function (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/');</code></pre>
<p>To run the server, put the code into a file called <code>example.js</code> and execute
it with the node program
</p>
<pre><code>> node example.js
Server running at http://127.0.0.1:8124/</code></pre>
<p>All of the examples in the documentation can be run similarly.
</p>
<h1>Global Objects<span><a class="mark" href="#all_global_objects" id="all_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>
<h2>global<span><a class="mark" href="#all_global" id="all_global">#</a></span></h2>
<!-- type=global -->
<ul>
<li>{Object} 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 this is different. The top-level scope is not the global
scope; <code>var something</code> inside a Node module will be local to that module.
</p>
<h2>process<span><a class="mark" href="#all_process" id="all_process">#</a></span></h2>
<!-- type=global -->
<ul>
<li>{Object}</li>
</ul>
<p>The process object. See the <a href="process.html#process_process">process object</a> section.
</p>
<h2>console<span><a class="mark" href="#all_console" id="all_console">#</a></span></h2>
<!-- type=global -->
<ul>
<li>{Object}</li>
</ul>
<p>Used to print to stdout and stderr. See the <a href="console.html">console</a> section.
</p>
<h2>Class: Buffer<span><a class="mark" href="#all_class_buffer" id="all_class_buffer">#</a></span></h2>
<!-- type=global -->
<ul>
<li>{Function}</li>
</ul>
<p>Used to handle binary data. See the <a href="buffer.html">buffer section</a>
</p>
<h2>require()<span><a class="mark" href="#all_require" id="all_require">#</a></span></h2>
<!-- type=var -->
<ul>
<li>{Function}</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.resolve()<span><a class="mark" href="#all_require_resolve" id="all_require_resolve">#</a></span></h3>
<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>
<h3>require.cache<span><a class="mark" href="#all_require_cache" id="all_require_cache">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">Object</span></li>
</div></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.
</p>
<h3>require.extensions<span><a class="mark" href="#all_require_extensions" id="all_require_extensions">#</a></span></h3>
<pre class="api_stability_0">Stability: 0 - Deprecated</pre><div class="signature"><ul>
<li><span class="type">Object</span></li>
</div></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>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 by compiling them on-demand.
However, in practice, there are much better ways to do this, such as
loading modules via some other Node 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>
<h2>__filename<span><a class="mark" href="#all_filename" id="all_filename">#</a></span></h2>
<!-- type=var -->
<ul>
<li>{String}</li>
</ul>
<p>The filename of the code being executed. This is the resolved absolute path
of this code file. For a main program this is not necessarily the same
filename used in the command line. The value inside a module is the path
to that module file.
</p>
<p>Example: running <code>node example.js</code> from <code>/Users/mjr</code>
</p>
<pre><code>console.log(__filename);
// /Users/mjr/example.js</code></pre>
<p><code>__filename</code> isn't actually a global but rather local to each module.
</p>
<h2>__dirname<span><a class="mark" href="#all_dirname" id="all_dirname">#</a></span></h2>
<!-- type=var -->
<ul>
<li>{String}</li>
</ul>
<p>The name of the directory that the currently executing script resides in.
</p>
<p>Example: running <code>node example.js</code> from <code>/Users/mjr</code>
</p>
<pre><code>console.log(__dirname);
// /Users/mjr</code></pre>
<p><code>__dirname</code> isn't actually a global but rather local to each module.
</p>
<h2>module<span><a class="mark" href="#all_module" id="all_module">#</a></span></h2>
<!-- type=var -->
<ul>
<li>{Object}</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>exports<span><a class="mark" href="#all_exports" id="all_exports">#</a></span></h2>
<!-- 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>
<p>See the <a href="modules.html">module section</a> for more information.
</p>
<h2>setTimeout(cb, ms)<span><a class="mark" href="#all_settimeout_cb_ms" id="all_settimeout_cb_ms">#</a></span></h2>
<p>Run callback <code>cb</code> after <em>at least</em> <code>ms</code> milliseconds. The actual delay depends
on external factors like OS timer granularity and system load.
</p>
<p>The timeout must be in the range of 1-2,147,483,647 inclusive. If the value is
outside that range, it's changed to 1 millisecond. Broadly speaking, a timer
cannot span more than 24.8 days.
</p>
<p>Returns an opaque value that represents the timer.
</p>
<h2>clearTimeout(t)<span><a class="mark" href="#all_cleartimeout_t" id="all_cleartimeout_t">#</a></span></h2>
<p>Stop a timer that was previously created with <code>setTimeout()</code>. The callback will
not execute.
</p>
<h2>setInterval(cb, ms)<span><a class="mark" href="#all_setinterval_cb_ms" id="all_setinterval_cb_ms">#</a></span></h2>
<p>Run callback <code>cb</code> repeatedly every <code>ms</code> milliseconds. Note that the actual
interval may vary, depending on external factors like OS timer granularity and
system load. It's never less than <code>ms</code> but it may be longer.
</p>
<p>The interval must be in the range of 1-2,147,483,647 inclusive. If the value is
outside that range, it's changed to 1 millisecond. Broadly speaking, a timer
cannot span more than 24.8 days.
</p>
<p>Returns an opaque value that represents the timer.
</p>
<h2>clearInterval(t)<span><a class="mark" href="#all_clearinterval_t" id="all_clearinterval_t">#</a></span></h2>
<p>Stop a timer that was previously created with <code>setInterval()</code>. The callback
will not execute.
</p>
<!--type=global-->
<p>The timer functions are global variables. See the <a href="timers.html">timers</a> section.
</p>
<h1>console<span><a class="mark" href="#all_console_1" id="all_console_1">#</a></span></h1>
<pre class="api_stability_4">Stability: 4 - API Frozen</pre><div class="signature"><ul>
<li><span class="type">Object</span></li>
</div></ul>
<!--type=global-->
<p>For printing to stdout and stderr. Similar to the console object functions
provided by most web browsers, here the output is sent to stdout or stderr.
</p>
<p>The console functions are synchronous when the destination is a terminal or
a file (to avoid lost messages in case of premature exit) and asynchronous
when it's a pipe (to avoid blocking for long periods of time).
</p>
<p>That is, in the following example, stdout is non-blocking while stderr
is blocking:
</p>
<pre><code>$ node script.js 2> error.log | tee info.log</code></pre>
<p>In daily use, the blocking/non-blocking dichotomy is not something you
should worry about unless you log huge amounts of data.
</p>
<h2>console.log([data], [...])<span><a class="mark" href="#all_console_log_data" id="all_console_log_data">#</a></span></h2>
<p>Prints to stdout with newline. This function can take multiple arguments in a
<code>printf()</code>-like way. Example:
</p>
<pre><code>console.log('count: %d', count);</code></pre>
<p>If formatting elements are not found in the first string then <code>util.inspect</code>
is used on each argument. See <a href="util.html#util_util_format_format">util.format()</a> for more information.
</p>
<h2>console.info([data], [...])<span><a class="mark" href="#all_console_info_data" id="all_console_info_data">#</a></span></h2>
<p>Same as <code>console.log</code>.
</p>
<h2>console.error([data], [...])<span><a class="mark" href="#all_console_error_data" id="all_console_error_data">#</a></span></h2>
<p>Same as <code>console.log</code> but prints to stderr.
</p>
<h2>console.warn([data], [...])<span><a class="mark" href="#all_console_warn_data" id="all_console_warn_data">#</a></span></h2>
<p>Same as <code>console.error</code>.
</p>
<h2>console.dir(obj)<span><a class="mark" href="#all_console_dir_obj" id="all_console_dir_obj">#</a></span></h2>
<p>Uses <code>util.inspect</code> on <code>obj</code> and prints resulting string to stdout.
</p>
<h2>console.time(label)<span><a class="mark" href="#all_console_time_label" id="all_console_time_label">#</a></span></h2>
<p>Mark a time.
</p>
<h2>console.timeEnd(label)<span><a class="mark" href="#all_console_timeend_label" id="all_console_timeend_label">#</a></span></h2>
<p>Finish timer, record output. Example:
</p>
<pre><code>console.time('100-elements');
for (var i = 0; i < 100; i++) {
;
}
console.timeEnd('100-elements');</code></pre>
<h2>console.trace(label)<span><a class="mark" href="#all_console_trace_label" id="all_console_trace_label">#</a></span></h2>
<p>Print a stack trace to stderr of the current position.
</p>
<h2>console.assert(expression, [message])<span><a class="mark" href="#all_console_assert_expression_message" id="all_console_assert_expression_message">#</a></span></h2>
<p>Same as <a href="assert.html#assert_assert_value_message_assert_ok_value_message">assert.ok()</a> where if the <code>expression</code> evaluates as <code>false</code> throw an
AssertionError with <code>message</code>.
</p>
<h1>Timers<span><a class="mark" href="#all_timers" id="all_timers">#</a></span></h1>
<pre class="api_stability_5">Stability: 5 - 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>setTimeout(callback, delay, [arg], [...])<span><a class="mark" href="#all_settimeout_callback_delay_arg" id="all_settimeout_callback_delay_arg">#</a></span></h2>
<p>To schedule execution of a one-time <code>callback</code> after <code>delay</code> milliseconds. Returns a
<code>timeoutObject</code> for possible use with <code>clearTimeout()</code>. Optionally you can
also pass arguments to the callback.
</p>
<p>It is important to note that your callback will probably not be called in exactly
<code>delay</code> milliseconds - Node.js makes no guarantees about the exact timing of when
the callback will fire, nor of the ordering things will fire in. The callback will
be called as close as possible to the time specified.
</p>
<h2>clearTimeout(timeoutObject)<span><a class="mark" href="#all_cleartimeout_timeoutobject" id="all_cleartimeout_timeoutobject">#</a></span></h2>
<p>Prevents a timeout from triggering.
</p>
<h2>setInterval(callback, delay, [arg], [...])<span><a class="mark" href="#all_setinterval_callback_delay_arg" id="all_setinterval_callback_delay_arg">#</a></span></h2>
<p>To schedule the repeated execution of <code>callback</code> every <code>delay</code> milliseconds.
Returns a <code>intervalObject</code> for possible use with <code>clearInterval()</code>. Optionally
you can also pass arguments to the callback.
</p>
<h2>clearInterval(intervalObject)<span><a class="mark" href="#all_clearinterval_intervalobject" id="all_clearinterval_intervalobject">#</a></span></h2>
<p>Stops a interval from triggering.
</p>
<h2>unref()<span><a class="mark" href="#all_unref" id="all_unref">#</a></span></h2>
<p>The opaque value returned by <code>setTimeout</code> and <code>setInterval</code> also has the method
<code>timer.unref()</code> which will allow you to create a timer that is active but if
it is the only item left in the event loop 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 <code>setTimeout</code> when you <code>unref</code> you create a separate timer that
will wakeup the event loop, creating too many of these may adversely effect
event loop performance -- use wisely.
</p>
<h2>ref()<span><a class="mark" href="#all_ref" id="all_ref">#</a></span></h2>
<p>If you had previously <code>unref()</code>d a timer you can call <code>ref()</code> 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>
<h2>setImmediate(callback, [arg], [...])<span><a class="mark" href="#all_setimmediate_callback_arg" id="all_setimmediate_callback_arg">#</a></span></h2>
<p>To schedule the "immediate" execution of <code>callback</code> after I/O events
callbacks and before <code>setTimeout</code> and <code>setInterval</code> . Returns an
<code>immediateObject</code> for possible use with <code>clearImmediate()</code>. Optionally you
can also pass arguments to the callback.
</p>
<p>Immediates are queued in the order created, and are popped off the queue once
per loop iteration. This is different from <code>process.nextTick</code> which will
execute <code>process.maxTickDepth</code> queued callbacks per iteration. <code>setImmediate</code>
will yield to the event loop after firing a queued callback to make sure I/O is
not being starved. While order is preserved for execution, other I/O events may
fire between any two scheduled immediate callbacks.
</p>
<h2>clearImmediate(immediateObject)<span><a class="mark" href="#all_clearimmediate_immediateobject" id="all_clearimmediate_immediateobject">#</a></span></h2>
<p>Stops an immediate from triggering.
</p>
<h1>Modules<span><a class="mark" href="#all_modules" id="all_modules">#</a></span></h1>
<pre class="api_stability_5">Stability: 5 - Locked</pre><!--name=module-->
<p>Node has a simple module loading system. In Node, files and modules are in
one-to-one correspondence. As an example, <code>foo.js</code> loads the module
<code>circle.js</code> in the same directory.
</p>
<p>The contents of <code>foo.js</code>:
</p>
<pre><code>var circle = require('./circle.js');
console.log( 'The area of a circle of radius 4 is '
+ circle.area(4));</code></pre>
<p>The contents of <code>circle.js</code>:
</p>
<pre><code>var PI = Math.PI;
exports.area = function (r) {
return PI * r * r;
};
exports.circumference = function (r) {
return 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, as though the module was wrapped
in a function. 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>var 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>// assigning to exports will not modify module, must use module.exports
module.exports = function(width) {
return {
area: function() {
return width * width;
}
};
}</code></pre>
<p>The module system is implemented in the <code>require("module")</code> module.
</p>
<h2>Cycles<span><a class="mark" href="#all_cycles" id="all_cycles">#</a></span></h2>
<!--type=misc-->
<p>When there are circular <code>require()</code> calls, a module might not be
done being executed 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;
var 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;
var 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');
var a = require('./a.js');
var 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>Core Modules<span><a class="mark" href="#all_core_modules" id="all_core_modules">#</a></span></h2>
<!--type=misc-->
<p>Node 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 in node's source 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>File Modules<span><a class="mark" href="#all_file_modules" id="all_file_modules">#</a></span></h2>
<!--type=misc-->
<p>If the exact filename is not found, then node will attempt to load the
required filename with the added extension of <code>.js</code>, <code>.json</code>, and then <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 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 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 is either 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 Error with its
<code>code</code> property set to <code>'MODULE_NOT_FOUND'</code>.
</p>
<h2>Loading from <code>node_modules</code> Folders<span><a class="mark" href="#all_loading_from_node_modules_folders" id="all_loading_from_node_modules_folders">#</a></span></h2>
<!--type=misc-->
<p>If the module identifier passed to <code>require()</code> is not a native module,
and does not begin with <code>'/'</code>, <code>'../'</code>, or <code>'./'</code>, then node starts at the
parent directory of the current module, and adds <code>/node_modules</code>, and
attempts to load the module from that location.
</p>
<p>If it is not found there, then it moves to the parent directory, and so
on, until the root of the tree 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 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>
<h2>Folders as Modules<span><a class="mark" href="#all_folders_as_modules" id="all_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's awareness of package.json files.
</p>
<p>If there is no package.json file present in the directory, then node
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>Caching<span><a class="mark" href="#all_caching" id="all_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="#all_module_caching_caveats" id="all_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>
<h2>The <code>module</code> Object<span><a class="mark" href="#all_the_module_object" id="all_the_module_object">#</a></span></h2>
<!-- type=var -->
<!-- name=module -->
<ul>
<li>{Object}</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.exports<span><a class="mark" href="#all_module_exports" id="all_module_exports">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">Object</span></li>
</div></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>var EventEmitter = require('events').EventEmitter;
module.exports = new EventEmitter();
// Do some work, and after some time emit
// the 'ready' event from the module itself.
setTimeout(function() {
module.exports.emit('ready');
}, 1000);</code></pre>
<p>Then in another file we could do
</p>
<pre><code>var a = require('./a');
a.on('ready', function() {
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>setTimeout(function() {
module.exports = { a: "hello" };
}, 0);</code></pre>
<p>y.js:
</p>
<pre><code>var x = require('./x');
console.log(x.a);</code></pre>
<h4>exports alias<span><a class="mark" href="#all_exports_alias" id="all_exports_alias">#</a></span></h4>
<p>The <code>exports</code> variable that is available within a module starts as a reference
to <code>module.exports</code>. As with any variable, if you assign a new value to it, it
is no longer bound to the previous value.
</p>
<p>To illustrate the behaviour, imagine this hypothetical implementation of
<code>require()</code>:
</p>
<pre><code>function require(...) {
// ...
function (module, exports) {
// Your module code here
exports = some_func; // re-assigns exports, exports is no longer
// a shortcut, and nothing is exported.
module.exports = some_func; // makes your module export 0
} (module, module.exports);
return module;
}</code></pre>
<p>As a guideline, if the relationship between <code>exports</code> and <code>module.exports</code>
seems like magic to you, ignore <code>exports</code> and only use <code>module.exports</code>.
</p>
<h3>module.require(id)<span><a class="mark" href="#all_module_require_id" id="all_module_require_id">#</a></span></h3>
<div class="signature"><ul>
<li><code>id</code> <span class="type">String</span></li>
<li>Return: <span class="type">Object</span> <code>module.exports</code> from the resolved module</li>
</div></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>
<h3>module.id<span><a class="mark" href="#all_module_id" id="all_module_id">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">String</span></li>
</div></ul>
<p>The identifier for the module. Typically this is the fully resolved
filename.
</p>
<h3>module.filename<span><a class="mark" href="#all_module_filename" id="all_module_filename">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">String</span></li>
</div></ul>
<p>The fully resolved filename to the module.
</p>
<h3>module.loaded<span><a class="mark" href="#all_module_loaded" id="all_module_loaded">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">Boolean</span></li>
</div></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="#all_module_parent" id="all_module_parent">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">Module Object</span></li>
</div></ul>
<p>The module that required this one.
</p>
<h3>module.children<span><a class="mark" href="#all_module_children" id="all_module_children">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">Array</span></li>
</div></ul>
<p>The module objects required by this one.
</p>
<h2>All Together...<span><a class="mark" href="#all_all_together" id="all_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.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.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 ROOT = index of first instance of "node_modules" in PARTS, or 0
3. let I = count of PARTS - 1
4. let DIRS = []
5. while I > ROOT,
a. if PARTS[I] = "node_modules" CONTINUE
c. DIR = path join(PARTS[0 .. I] + "node_modules")
b. DIRS = DIRS + DIR
c. let I = I - 1
6. return DIRS</code></pre>
<h2>Loading from the global folders<span><a class="mark" href="#all_loading_from_the_global_folders" id="all_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 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>Additionally, node 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's
configured <code>node_prefix</code>.
</p>
<p>These are mostly for historic reasons. You are highly encouraged to
place your dependencies locally in <code>node_modules</code> folders. They will be
loaded faster, and more reliably.
</p>
<h2>Accessing the main module<span><a class="mark" href="#all_accessing_the_main_module" id="all_accessing_the_main_module">#</a></span></h2>
<!-- type=misc -->
<p>When a file is run directly from Node, <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>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="#all_addenda_package_manager_tips" id="all_addenda_package_manager_tips">#</a></span></h2>
<!-- type=misc -->
<p>The semantics of Node's <code>require()</code> function were designed to be general
enough to support a number of sane 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 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 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 above, 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 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 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>
<h1>Addons<span><a class="mark" href="#all_addons" id="all_addons">#</a></span></h1>
<p>Addons are dynamically linked shared objects. They can provide glue to C and
C++ libraries. The API (at the moment) is rather complex, involving
knowledge of several libraries:
</p>
<ul>
<li><p>V8 JavaScript, a C++ library. Used for interfacing with JavaScript:
creating objects, calling functions, etc. Documented mostly in the
<code>v8.h</code> header file (<code>deps/v8/include/v8.h</code> in the Node source
tree), which is also available
<a href="http://izs.me/v8-docs/main.html">online</a>.</p>
</li>
<li><p><a href="https://github.com/joyent/libuv">libuv</a>, C event loop library.
Anytime one needs to wait for a file descriptor to become readable,
wait for a timer, or wait for a signal to be received one will need
to interface with libuv. That is, if you perform any I/O, libuv will
need to be used.</p>
</li>
<li><p>Internal Node libraries. Most importantly is the <code>node::ObjectWrap</code>
class which you will likely want to derive from.</p>
</li>
<li><p>Others. Look in <code>deps/</code> for what else is available.</p>
</li>
</ul>
<p>Node statically compiles all its dependencies into the executable.
When compiling your module, you don't need to worry about linking to
any of these libraries.
</p>
<p>All of the following examples are available for
<a href="https://github.com/rvagg/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="#all_hello_world" id="all_hello_world">#</a></span></h2>
<p>To get started let's make a small Addon which is the C++ equivalent of
the following JavaScript code:
</p>
<pre><code>module.exports.hello = function() { return 'world'; };</code></pre>
<p>First we create a file <code>hello.cc</code>:
</p>
<pre><code>#include <node.h>
#include <v8.h>
using namespace v8;
Handle<Value> Method(const Arguments& args) {
HandleScope scope;
return scope.Close(String::New("world"));
}
void init(Handle<Object> exports) {
exports->Set(String::NewSymbol("hello"),
FunctionTemplate::New(Method)->GetFunction());
}
NODE_MODULE(hello, init)</code></pre>
<p>Note that all Node addons must export an initialization function:
</p>
<pre><code>void Initialize (Handle<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> needs to match the filename of the final binary (minus the
.node suffix).
</p>
<p>The source code needs to be built into <code>hello.node</code>, the binary Addon. To
do this we create a file called <code>binding.gyp</code> which describes the configuration
to build your module in a JSON-like format. This file gets compiled by
<a href="https://github.com/TooTallNate/node-gyp">node-gyp</a>.
</p>
<pre><code>{
"targets": [
{
"target_name": "hello",
"sources": [ "hello.cc" ]
}
]
}</code></pre>
<p>The next step is to generate the appropriate project build files for the
current platform. Use <code>node-gyp configure</code> for that.
</p>
<p>Now you will have either a <code>Makefile</code> (on Unix platforms) or a <code>vcxproj</code> file
(on Windows) in the <code>build/</code> directory. Next invoke the <code>node-gyp build</code>
command.
</p>
<p>Now you have your compiled <code>.node</code> bindings file! The compiled bindings end up
in <code>build/Release/</code>.
</p>
<p>You can now use the binary addon in a Node project <code>hello.js</code> by pointing <code>require</code> to
the recently built <code>hello.node</code> module:
</p>
<pre><code>var addon = require('./build/Release/hello');
console.log(addon.hello()); // 'world'</code></pre>
<p>Please see patterns below for further information or
</p>
<p><a href="https://github.com/arturadib/node-qt">https://github.com/arturadib/node-qt</a> for an example in production.
</p>
<h2>Addon patterns<span><a class="mark" href="#all_addon_patterns" id="all_addon_patterns">#</a></span></h2>
<p>Below are some addon patterns to help you get started. Consult the online
<a href="http://izs.me/v8-docs/main.html">v8 reference</a> for help with the various v8
calls, and v8's <a href="http://code.google.com/apis/v8/embed.html">Embedder's Guide</a>
for an explanation of several concepts used such as handles, scopes,
function templates, etc.
</p>
<p>In order to use these examples you need to compile them using <code>node-gyp</code>.
Create 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 file name to the
<code>sources</code> array, e.g.:
</p>
<pre><code>"sources": ["addon.cc", "myexample.cc"]</code></pre>
<p>Now that you have your <code>binding.gyp</code> ready, you can configure and build the
addon:
</p>
<pre><code>$ node-gyp configure build</code></pre>
<h3>Function arguments<span><a class="mark" href="#all_function_arguments" id="all_function_arguments">#</a></span></h3>
<p>The following pattern illustrates how to read arguments from JavaScript
function calls and return a result. This is the main and only needed source
<code>addon.cc</code>:
</p>
<pre><code>#define BUILDING_NODE_EXTENSION
#include <node.h>
using namespace v8;
Handle<Value> Add(const Arguments& args) {
HandleScope scope;
if (args.Length() < 2) {
ThrowException(Exception::TypeError(String::New("Wrong number of arguments")));
return scope.Close(Undefined());
}
if (!args[0]->IsNumber() || !args[1]->IsNumber()) {
ThrowException(Exception::TypeError(String::New("Wrong arguments")));
return scope.Close(Undefined());
}
Local<Number> num = Number::New(args[0]->NumberValue() +
args[1]->NumberValue());
return scope.Close(num);
}
void Init(Handle<Object> exports) {
exports->Set(String::NewSymbol("add"),
FunctionTemplate::New(Add)->GetFunction());
}
NODE_MODULE(addon, Init)</code></pre>
<p>You can test it with the following JavaScript snippet:
</p>
<pre><code>var addon = require('./build/Release/addon');
console.log( 'This should be eight:', addon.add(3,5) );</code></pre>
<h3>Callbacks<span><a class="mark" href="#all_callbacks" id="all_callbacks">#</a></span></h3>
<p>You can pass JavaScript functions to a C++ function and execute them from
there. Here's <code>addon.cc</code>:
</p>
<pre><code>#define BUILDING_NODE_EXTENSION
#include <node.h>
using namespace v8;
Handle<Value> RunCallback(const Arguments& args) {
HandleScope scope;
Local<Function> cb = Local<Function>::Cast(args[0]);
const unsigned argc = 1;
Local<Value> argv[argc] = { Local<Value>::New(String::New("hello world")) };
cb->Call(Context::GetCurrent()->Global(), argc, argv);
return scope.Close(Undefined());
}
void Init(Handle<Object> exports, Handle<Object> module) {
module->Set(String::NewSymbol("exports"),
FunctionTemplate::New(RunCallback)->GetFunction());
}
NODE_MODULE(addon, Init)</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 snippet:
</p>
<pre><code>var addon = require('./build/Release/addon');
addon(function(msg){
console.log(msg); // 'hello world'
});</code></pre>
<h3>Object factory<span><a class="mark" href="#all_object_factory" id="all_object_factory">#</a></span></h3>
<p>You can create and return new objects from within a C++ function with this
<code>addon.cc</code> pattern, which returns an object with property <code>msg</code> that echoes
the string passed to <code>createObject()</code>:
</p>
<pre><code>#define BUILDING_NODE_EXTENSION
#include <node.h>
using namespace v8;
Handle<Value> CreateObject(const Arguments& args) {
HandleScope scope;
Local<Object> obj = Object::New();
obj->Set(String::NewSymbol("msg"), args[0]->ToString());
return scope.Close(obj);
}
void Init(Handle<Object> exports, Handle<Object> module) {
module->Set(String::NewSymbol("exports"),
FunctionTemplate::New(CreateObject)->GetFunction());
}
NODE_MODULE(addon, Init)</code></pre>
<p>To test it in JavaScript:
</p>
<pre><code>var 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="#all_function_factory" id="all_function_factory">#</a></span></h3>
<p>This pattern illustrates how to create and return a JavaScript function that
wraps a C++ function:
</p>
<pre><code>#define BUILDING_NODE_EXTENSION
#include <node.h>
using namespace v8;
Handle<Value> MyFunction(const Arguments& args) {
HandleScope scope;
return scope.Close(String::New("hello world"));
}
Handle<Value> CreateFunction(const Arguments& args) {
HandleScope scope;
Local<FunctionTemplate> tpl = FunctionTemplate::New(MyFunction);
Local<Function> fn = tpl->GetFunction();
fn->SetName(String::NewSymbol("theFunction")); // omit this to make it anonymous
return scope.Close(fn);
}
void Init(Handle<Object> exports, Handle<Object> module) {
module->Set(String::NewSymbol("exports"),
FunctionTemplate::New(CreateFunction)->GetFunction());
}
NODE_MODULE(addon, Init)</code></pre>
<p>To test:
</p>
<pre><code>var addon = require('./build/Release/addon');
var fn = addon();
console.log(fn()); // 'hello world'</code></pre>
<h3>Wrapping C++ objects<span><a class="mark" href="#all_wrapping_c_objects" id="all_wrapping_c_objects">#</a></span></h3>
<p>Here we will create a wrapper for a C++ object/class <code>MyObject</code> that can be
instantiated in JavaScript through the <code>new</code> operator. First prepare the main
module <code>addon.cc</code>:
</p>
<pre><code>#define BUILDING_NODE_EXTENSION
#include <node.h>
#include "myobject.h"
using namespace v8;
void InitAll(Handle<Object> exports) {
MyObject::Init(exports);
}
NODE_MODULE(addon, InitAll)</code></pre>
<p>Then in <code>myobject.h</code> make your wrapper inherit from <code>node::ObjectWrap</code>:
</p>
<pre><code>#ifndef MYOBJECT_H
#define MYOBJECT_H
#include <node.h>
class MyObject : public node::ObjectWrap {
public:
static void Init(v8::Handle<v8::Object> exports);
private:
explicit MyObject(double value = 0);
~MyObject();
static v8::Handle<v8::Value> New(const v8::Arguments& args);
static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);
static v8::Persistent<v8::Function> constructor;
double value_;
};
#endif</code></pre>
<p>And in <code>myobject.cc</code> implement the various methods that you want to expose.
Here we expose the method <code>plusOne</code> by adding it to the constructor's
prototype:
</p>
<pre><code>#define BUILDING_NODE_EXTENSION
#include <node.h>
#include "myobject.h"
using namespace v8;
Persistent<Function> MyObject::constructor;
MyObject::MyObject(double value) : value_(value) {
}
MyObject::~MyObject() {
}
void MyObject::Init(Handle<Object> exports) {
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
tpl->SetClassName(String::NewSymbol("MyObject"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),
FunctionTemplate::New(PlusOne)->GetFunction());
constructor = Persistent<Function>::New(tpl->GetFunction());
exports->Set(String::NewSymbol("MyObject"), constructor);
}
Handle<Value> MyObject::New(const Arguments& args) {
HandleScope scope;
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());
return args.This();
} else {
// Invoked as plain function `MyObject(...)`, turn into construct call.
const int argc = 1;
Local<Value> argv[argc] = { args[0] };
return scope.Close(constructor->NewInstance(argc, argv));
}
}
Handle<Value> MyObject::PlusOne(const Arguments& args) {
HandleScope scope;
MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());
obj->value_ += 1;
return scope.Close(Number::New(obj->value_));
}</code></pre>
<p>Test it with:
</p>
<pre><code>var 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="#all_factory_of_wrapped_objects" id="all_factory_of_wrapped_objects">#</a></span></h3>
<p>This is useful when you want to be able to create native objects without
explicitly instantiating them with the <code>new</code> operator in JavaScript, e.g.
</p>
<pre><code>var obj = addon.createObject();
// instead of:
// var obj = new addon.Object();</code></pre>
<p>Let's register our <code>createObject</code> method in <code>addon.cc</code>:
</p>
<pre><code>#define BUILDING_NODE_EXTENSION
#include <node.h>
#include "myobject.h"
using namespace v8;
Handle<Value> CreateObject(const Arguments& args) {
HandleScope scope;
return scope.Close(MyObject::NewInstance(args));
}
void InitAll(Handle<Object> exports, Handle<Object> module) {
MyObject::Init();
module->Set(String::NewSymbol("exports"),
FunctionTemplate::New(CreateObject)->GetFunction());
}
NODE_MODULE(addon, InitAll)</code></pre>
<p>In <code>myobject.h</code> we now introduce the static method <code>NewInstance</code> that takes
care of instantiating the object (i.e. it does the job of <code>new</code> in JavaScript):
</p>
<pre><code>#define BUILDING_NODE_EXTENSION
#ifndef MYOBJECT_H
#define MYOBJECT_H
#include <node.h>
class MyObject : public node::ObjectWrap {
public:
static void Init();
static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);
private:
explicit MyObject(double value = 0);
~MyObject();
static v8::Handle<v8::Value> New(const v8::Arguments& args);
static v8::Handle<v8::Value> PlusOne(const v8::Arguments& args);
static v8::Persistent<v8::Function> constructor;
double value_;
};
#endif</code></pre>
<p>The implementation is similar to the above in <code>myobject.cc</code>:
</p>
<pre><code>#define BUILDING_NODE_EXTENSION
#include <node.h>
#include "myobject.h"
using namespace v8;
Persistent<Function> MyObject::constructor;
MyObject::MyObject(double value) : value_(value) {
}
MyObject::~MyObject() {
}
void MyObject::Init() {
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
tpl->SetClassName(String::NewSymbol("MyObject"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
// Prototype
tpl->PrototypeTemplate()->Set(String::NewSymbol("plusOne"),
FunctionTemplate::New(PlusOne)->GetFunction());
constructor = Persistent<Function>::New(tpl->GetFunction());
}
Handle<Value> MyObject::New(const Arguments& args) {
HandleScope scope;
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());
return args.This();
} else {
// Invoked as plain function `MyObject(...)`, turn into construct call.
const int argc = 1;
Local<Value> argv[argc] = { args[0] };
return scope.Close(constructor->NewInstance(argc, argv));
}
}
Handle<Value> MyObject::NewInstance(const Arguments& args) {
HandleScope scope;
const unsigned argc = 1;
Handle<Value> argv[argc] = { args[0] };
Local<Object> instance = constructor->NewInstance(argc, argv);
return scope.Close(instance);
}
Handle<Value> MyObject::PlusOne(const Arguments& args) {
HandleScope scope;
MyObject* obj = ObjectWrap::Unwrap<MyObject>(args.This());
obj->value_ += 1;
return scope.Close(Number::New(obj->value_));
}</code></pre>
<p>Test it with:
</p>
<pre><code>var 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="#all_passing_wrapped_objects_around" id="all_passing_wrapped_objects_around">#</a></span></h3>
<p>In addition to wrapping and returning C++ objects, you can pass them around
by unwrapping them with Node's <code>node::ObjectWrap::Unwrap</code> helper function.
In the following <code>addon.cc</code> we introduce a function <code>add()</code> that can take on two
<code>MyObject</code> objects:
</p>
<pre><code>#define BUILDING_NODE_EXTENSION
#include <node.h>
#include "myobject.h"
using namespace v8;
Handle<Value> CreateObject(const Arguments& args) {
HandleScope scope;
return scope.Close(MyObject::NewInstance(args));
}
Handle<Value> Add(const Arguments& args) {
HandleScope scope;
MyObject* obj1 = node::ObjectWrap::Unwrap<MyObject>(
args[0]->ToObject());
MyObject* obj2 = node::ObjectWrap::Unwrap<MyObject>(
args[1]->ToObject());
double sum = obj1->Value() + obj2->Value();
return scope.Close(Number::New(sum));
}
void InitAll(Handle<Object> exports) {
MyObject::Init();
exports->Set(String::NewSymbol("createObject"),
FunctionTemplate::New(CreateObject)->GetFunction());
exports->Set(String::NewSymbol("add"),
FunctionTemplate::New(Add)->GetFunction());
}
NODE_MODULE(addon, InitAll)</code></pre>
<p>To make things interesting we introduce a public method in <code>myobject.h</code> so we
can probe private values after unwrapping the object:
</p>
<pre><code>#define BUILDING_NODE_EXTENSION
#ifndef MYOBJECT_H
#define MYOBJECT_H
#include <node.h>
class MyObject : public node::ObjectWrap {
public:
static void Init();
static v8::Handle<v8::Value> NewInstance(const v8::Arguments& args);
double Value() const { return value_; }
private:
explicit MyObject(double value = 0);
~MyObject();
static v8::Handle<v8::Value> New(const v8::Arguments& args);
static v8::Persistent<v8::Function> constructor;
double value_;
};
#endif</code></pre>
<p>The implementation of <code>myobject.cc</code> is similar as before:
</p>
<pre><code>#define BUILDING_NODE_EXTENSION
#include <node.h>
#include "myobject.h"
using namespace v8;
Persistent<Function> MyObject::constructor;
MyObject::MyObject(double value) : value_(value) {
}
MyObject::~MyObject() {
}
void MyObject::Init() {
// Prepare constructor template
Local<FunctionTemplate> tpl = FunctionTemplate::New(New);
tpl->SetClassName(String::NewSymbol("MyObject"));
tpl->InstanceTemplate()->SetInternalFieldCount(1);
constructor = Persistent<Function>::New(tpl->GetFunction());
}
Handle<Value> MyObject::New(const Arguments& args) {
HandleScope scope;
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());
return args.This();
} else {
// Invoked as plain function `MyObject(...)`, turn into construct call.
const int argc = 1;
Local<Value> argv[argc] = { args[0] };
return scope.Close(constructor->NewInstance(argc, argv));
}
}
Handle<Value> MyObject::NewInstance(const Arguments& args) {
HandleScope scope;
const unsigned argc = 1;
Handle<Value> argv[argc] = { args[0] };
Local<Object> instance = constructor->NewInstance(argc, argv);
return scope.Close(instance);
}</code></pre>
<p>Test it with:
</p>
<pre><code>var 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>
<h1>process<span><a class="mark" href="#all_process_1" id="all_process_1">#</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_events_eventemitter">EventEmitter</a>.
</p>
<h2>Event: 'exit'<span><a class="mark" href="#all_event_exit" id="all_event_exit">#</a></span></h2>
<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>Example of listening for <code>exit</code>:
</p>
<pre><code>process.on('exit', function(code) {
// do *NOT* do this
setTimeout(function() {
console.log('This will not run');
}, 0);
console.log('About to exit with code:', code);
});</code></pre>
<h2>Event: 'uncaughtException'<span><a class="mark" href="#all_event_uncaughtexception" id="all_event_uncaughtexception">#</a></span></h2>
<p>Emitted when an exception bubbles all the way back to the event loop. If a
listener is added for this exception, the default action (which is to print
a stack trace and exit) will not occur.
</p>
<p>Example of listening for <code>uncaughtException</code>:
</p>
<pre><code>process.on('uncaughtException', function(err) {
console.log('Caught exception: ' + err);
});
setTimeout(function() {
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>
<p>Note that <code>uncaughtException</code> is a very crude mechanism for exception
handling and may be removed in the future.
</p>
<p>Don't use it, use <a href="domain.html">domains</a> instead. If you do use it, restart
your application after every unhandled exception!
</p>
<p>Do <em>not</em> use it as the node.js equivalent of <code>On Error Resume Next</code>. An
unhandled exception means your application - and by extension node.js itself -
is in an undefined state. Blindly resuming means <em>anything</em> could happen.
</p>
<p>Think of resuming as pulling the power cord when you are upgrading your system.
Nine out of ten times nothing happens - but the 10th time, your system is bust.
</p>
<p>You have been warned.
</p>
<h2>Signal Events<span><a class="mark" href="#all_signal_events" id="all_signal_events">#</a></span></h2>
<!--type=event-->
<!--name=SIGINT, SIGHUP, etc.-->
<p>Emitted when the processes receives a signal. See sigaction(2) for a list of
standard POSIX signal names such as SIGINT, SIGHUP, etc.
</p>
<p>Example of listening for <code>SIGINT</code>:
</p>
<pre><code>// Start reading from stdin so we don't exit.
process.stdin.resume();
process.on('SIGINT', function() {
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 behaviour will be removed
(node 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 signal(7). It can have a
listener installed, however node will be unconditionally terminated by Windows
about 10 seconds later. On non-Windows platforms, the default behaviour of
<code>SIGHUP</code> is to terminate node, but once a listener has been installed its
default behaviour 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 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 offers some
emulation with <code>process.kill()</code>, and <code>child_process.kill()</code>:
- Sending signal <code>0</code> can be used to search for the existence of a process
- Sending <code>SIGINT</code>, <code>SIGTERM</code>, and <code>SIGKILL</code> cause the unconditional exit of the
target process.
</p>
<h2>process.stdout<span><a class="mark" href="#all_process_stdout" id="all_process_stdout">#</a></span></h2>
<p>A <code>Writable Stream</code> to <code>stdout</code>.
</p>
<p>Example: the definition of <code>console.log</code>
</p>
<pre><code>console.log = function(d) {
process.stdout.write(d + '\n');
};</code></pre>
<p><code>process.stderr</code> and <code>process.stdout</code> are unlike other streams in Node in
that writes to them are usually blocking.
</p>
<ul>
<li>They are blocking in the case that they refer to regular files or TTY file
descriptors.</li>
<li>In the case they refer to pipes:<ul>
<li>They are blocking in Linux/Unix.</li>
<li>They are non-blocking like other streams in Windows.</li>
</ul>
</li>
</ul>
<p>To check if Node 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.stderr<span><a class="mark" href="#all_process_stderr" id="all_process_stderr">#</a></span></h2>
<p>A writable stream to stderr.
</p>
<p><code>process.stderr</code> and <code>process.stdout</code> are unlike other streams in Node in
that writes to them are usually blocking.
</p>
<ul>
<li>They are blocking in the case that they refer to regular files or TTY file
descriptors.</li>
<li>In the case they refer to pipes:<ul>
<li>They are blocking in Linux/Unix.</li>
<li>They are non-blocking like other streams in Windows.</li>
</ul>
</li>
</ul>
<h2>process.stdin<span><a class="mark" href="#all_process_stdin" id="all_process_stdin">#</a></span></h2>
<p>A <code>Readable Stream</code> for stdin.
</p>
<p>Example of opening standard input and listening for both events:
</p>
<pre><code>process.stdin.setEncoding('utf8');
process.stdin.on('readable', function() {
var chunk = process.stdin.read();
if (chunk !== null) {
process.stdout.write('data: ' + chunk);
}
});
process.stdin.on('end', function() {
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 prior v0.10.
For more information see
<a href="stream.html#stream_compatibility_with_older_node_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.argv<span><a class="mark" href="#all_process_argv" id="all_process_argv">#</a></span></h2>
<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>// print process.argv
process.argv.forEach(function(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.execPath<span><a class="mark" href="#all_process_execpath" id="all_process_execpath">#</a></span></h2>
<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.execArgv<span><a class="mark" href="#all_process_execargv" id="all_process_execargv">#</a></span></h2>
<p>This is the set of node-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 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>['--harmony']</code></pre>
<p>and process.argv:
</p>
<pre><code>['/usr/local/bin/node', 'script.js', '--version']</code></pre>
<h2>process.abort()<span><a class="mark" href="#all_process_abort" id="all_process_abort">#</a></span></h2>
<p>This causes node to emit an abort. This will cause node to exit and
generate a core file.
</p>
<h2>process.chdir(directory)<span><a class="mark" href="#all_process_chdir_directory" id="all_process_chdir_directory">#</a></span></h2>
<p>Changes the current working directory of the process or throws an exception if that fails.
</p>
<pre><code>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.cwd()<span><a class="mark" href="#all_process_cwd" id="all_process_cwd">#</a></span></h2>
<p>Returns the current working directory of the process.
</p>
<pre><code>console.log('Current directory: ' + process.cwd());</code></pre>
<h2>process.env<span><a class="mark" href="#all_process_env" id="all_process_env">#</a></span></h2>
<p>An object containing the user environment. See environ(7).
</p>
<h2>process.exit([code])<span><a class="mark" href="#all_process_exit_code" id="all_process_exit_code">#</a></span></h2>
<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>process.exit(1);</code></pre>
<p>The shell that executed node should see the exit code as 1.
</p>
<h2>process.getgid()<span><a class="mark" href="#all_process_getgid" id="all_process_getgid">#</a></span></h2>
<p>Note: this function is only available on POSIX platforms (i.e. not Windows)
</p>
<p>Gets the group identity of the process. (See getgid(2).)
This is the numerical group id, not the group name.
</p>
<pre><code>if (process.getgid) {
console.log('Current gid: ' + process.getgid());
}</code></pre>
<h2>process.setgid(id)<span><a class="mark" href="#all_process_setgid_id" id="all_process_setgid_id">#</a></span></h2>
<p>Note: this function is only available on POSIX platforms (i.e. not Windows)
</p>
<p>Sets the group identity of the process. (See setgid(2).) 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>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.getuid()<span><a class="mark" href="#all_process_getuid" id="all_process_getuid">#</a></span></h2>
<p>Note: this function is only available on POSIX platforms (i.e. not Windows)
</p>
<p>Gets the user identity of the process. (See getuid(2).)
This is the numerical userid, not the username.
</p>
<pre><code>if (process.getuid) {
console.log('Current uid: ' + process.getuid());
}</code></pre>
<h2>process.setuid(id)<span><a class="mark" href="#all_process_setuid_id" id="all_process_setuid_id">#</a></span></h2>
<p>Note: this function is only available on POSIX platforms (i.e. not Windows)
</p>
<p>Sets the user identity of the process. (See setuid(2).) 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>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.getgroups()<span><a class="mark" href="#all_process_getgroups" id="all_process_getgroups">#</a></span></h2>
<p>Note: this function is only available on POSIX platforms (i.e. not Windows)
</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.setgroups(groups)<span><a class="mark" href="#all_process_setgroups_groups" id="all_process_setgroups_groups">#</a></span></h2>
<p>Note: this function is only available on POSIX platforms (i.e. not Windows)
</p>
<p>Sets the supplementary group IDs. This is a privileged operation, meaning you
need to be root or have the CAP_SETGID capability.
</p>
<p>The list can contain group IDs, group names or both.
</p>
<h2>process.initgroups(user, extra_group)<span><a class="mark" href="#all_process_initgroups_user_extra_group" id="all_process_initgroups_user_extra_group">#</a></span></h2>
<p>Note: this function is only available on POSIX platforms (i.e. not Windows)
</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 CAP_SETGID 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>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.version<span><a class="mark" href="#all_process_version" id="all_process_version">#</a></span></h2>
<p>A compiled-in property that exposes <code>NODE_VERSION</code>.
</p>
<pre><code>console.log('Version: ' + process.version);</code></pre>
<h2>process.versions<span><a class="mark" href="#all_process_versions" id="all_process_versions">#</a></span></h2>
<p>A property exposing version strings of node and its dependencies.
</p>
<pre><code>console.log(process.versions);</code></pre>
<p>Will print something like:
</p>
<pre><code>{ http_parser: '1.0',
node: '0.10.4',
v8: '3.14.5.8',
ares: '1.9.0-DEV',
uv: '0.10.3',
zlib: '1.2.3',
modules: '11',
openssl: '1.0.1e' }</code></pre>
<h2>process.config<span><a class="mark" href="#all_process_config" id="all_process_config">#</a></span></h2>
<p>An Object containing the JavaScript representation of the configure options
that were used to compile the current node executable. This is the same as
the "config.gypi" 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_v8: '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>
<h2>process.kill(pid, [signal])<span><a class="mark" href="#all_process_kill_pid_signal" id="all_process_kill_pid_signal">#</a></span></h2>
<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
'SIGINT' or 'SIGHUP'. If omitted, the signal will be 'SIGTERM'.
See <a href="#process_signal_events">Signal Events</a> and kill(2) 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.
</p>
<p>Note that just because 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>process.on('SIGHUP', function() {
console.log('Got SIGHUP signal.');
});
setTimeout(function() {
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.pid<span><a class="mark" href="#all_process_pid" id="all_process_pid">#</a></span></h2>
<p>The PID of the process.
</p>
<pre><code>console.log('This process is pid ' + process.pid);</code></pre>
<h2>process.title<span><a class="mark" href="#all_process_title" id="all_process_title">#</a></span></h2>
<p>Getter/setter to set what is displayed in 'ps'.
</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.arch<span><a class="mark" href="#all_process_arch" id="all_process_arch">#</a></span></h2>
<p>What processor architecture you're running on: <code>'arm'</code>, <code>'ia32'</code>, or <code>'x64'</code>.
</p>
<pre><code>console.log('This processor architecture is ' + process.arch);</code></pre>
<h2>process.platform<span><a class="mark" href="#all_process_platform" id="all_process_platform">#</a></span></h2>
<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>console.log('This platform is ' + process.platform);</code></pre>
<h2>process.memoryUsage()<span><a class="mark" href="#all_process_memoryusage" id="all_process_memoryusage">#</a></span></h2>
<p>Returns an object describing the memory usage of the Node process
measured in bytes.
</p>
<pre><code>var util = require('util');
console.log(util.inspect(process.memoryUsage()));</code></pre>
<p>This will generate:
</p>
<pre><code>{ rss: 4935680,
heapTotal: 1826816,
heapUsed: 650472 }</code></pre>
<p><code>heapTotal</code> and <code>heapUsed</code> refer to V8's memory usage.
</p>
<h2>process.nextTick(callback)<span><a class="mark" href="#all_process_nexttick_callback" id="all_process_nexttick_callback">#</a></span></h2>
<p>On the next loop around the event loop call this callback.
This is <em>not</em> a simple alias to <code>setTimeout(fn, 0)</code>, it's much more
efficient. It typically runs before any other I/O events fire, but there
are some exceptions. See <code>process.maxTickDepth</code> below.
</p>
<pre><code>process.nextTick(function() {
console.log('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>function MyThing(options) {
this.setupOptions(options);
process.nextTick(function() {
this.startDoingStuff();
}.bind(this));
}
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>// 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>maybeSync(true, function() {
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>function definitelyAsync(arg, cb) {
if (arg) {
process.nextTick(cb);
return;
}
fs.stat('file', cb);
}</code></pre>
<h2>process.maxTickDepth<span><a class="mark" href="#all_process_maxtickdepth" id="all_process_maxtickdepth">#</a></span></h2>
<div class="signature"><ul>
<li><span class="type">Number</span> Default = 1000</li>
</div></ul>
<p>Callbacks passed to <code>process.nextTick</code> will <em>usually</em> be called at the
end of the current flow of execution, and are thus approximately as fast
as calling a function synchronously. Left unchecked, this would starve
the event loop, preventing any I/O from occurring.
</p>
<p>Consider this code:
</p>
<pre><code>process.nextTick(function foo() {
process.nextTick(foo);
});</code></pre>
<p>In order to avoid the situation where Node is blocked by an infinite
loop of recursive series of nextTick calls, it defers to allow some I/O
to be done every so often.
</p>
<p>The <code>process.maxTickDepth</code> value is the maximum depth of
nextTick-calling nextTick-callbacks that will be evaluated before
allowing other forms of I/O to occur.
</p>
<h2>process.umask([mask])<span><a class="mark" href="#all_process_umask_mask" id="all_process_umask_mask">#</a></span></h2>
<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>var oldmask, newmask = 0644;
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="#all_process_uptime" id="all_process_uptime">#</a></span></h2>
<p>Number of seconds Node has been running.
</p>
<h2>process.hrtime()<span><a class="mark" href="#all_process_hrtime" id="all_process_hrtime">#</a></span></h2>
<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>var time = process.hrtime();
// [ 1800216, 25 ]
setTimeout(function() {
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>
<h1>util<span><a class="mark" href="#all_util" id="all_util">#</a></span></h1>
<pre class="api_stability_4">Stability: 4 - API Frozen</pre><p>These functions are in the module <code>'util'</code>. Use <code>require('util')</code> to access
them.
</p>
<h2>util.format(format, [...])<span><a class="mark" href="#all_util_format_format" id="all_util_format_format">#</a></span></h2>
<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.</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>util.format('%s:%s', 'foo'); // 'foo:%s'</code></pre>
<p>If there are more arguments than placeholders, the extra arguments are
converted to strings with <code>util.inspect()</code> and these strings are concatenated,
delimited by a space.
</p>
<pre><code>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>util.format(1, 2, 3); // '1 2 3'</code></pre>
<h2>util.debug(string)<span><a class="mark" href="#all_util_debug_string" id="all_util_debug_string">#</a></span></h2>
<p>A synchronous output function. Will block the process and
output <code>string</code> immediately to <code>stderr</code>.
</p>
<pre><code>require('util').debug('message on stderr');</code></pre>
<h2>util.error([...])<span><a class="mark" href="#all_util_error" id="all_util_error">#</a></span></h2>
<p>Same as <code>util.debug()</code> except this will output all arguments immediately to
<code>stderr</code>.
</p>
<h2>util.puts([...])<span><a class="mark" href="#all_util_puts" id="all_util_puts">#</a></span></h2>
<p>A synchronous output function. Will block the process and output all arguments
to <code>stdout</code> with newlines after each argument.
</p>
<h2>util.print([...])<span><a class="mark" href="#all_util_print" id="all_util_print">#</a></span></h2>
<p>A synchronous output function. Will block the process, cast each argument to a
string then output to <code>stdout</code>. Does not place newlines after each argument.
</p>
<h2>util.log(string)<span><a class="mark" href="#all_util_log_string" id="all_util_log_string">#</a></span></h2>
<p>Output with timestamp on <code>stdout</code>.
</p>
<pre><code>require('util').log('Timestamped message.');</code></pre>
<h2>util.inspect(object, [options])<span><a class="mark" href="#all_util_inspect_object_options" id="all_util_inspect_object_options">#</a></span></h2>
<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 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 below.</p>
</li>
<li><p><code>customInspect</code> - if <code>false</code>, then custom <code>inspect()</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>var util = require('util');
console.log(util.inspect(util, { showHidden: true, depth: null }));</code></pre>
<h3>Customizing <code>util.inspect</code> colors<span><a class="mark" href="#all_customizing_util_inspect_colors" id="all_customizing_util_inspect_colors">#</a></span></h3>
<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:
<em> <code>number</code> (yellow)
</em> <code>boolean</code> (yellow)
<em> <code>string</code> (green)
</em> <code>date</code> (magenta)
<em> <code>regexp</code> (red)
</em> <code>null</code> (bold)
<em> <code>undefined</code> (grey)
</em> <code>special</code> - only function at this time (cyan)
* <code>name</code> (intentionally no styling)
</p>
<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>
<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>var util = require('util');
var obj = { name: 'nate' };
obj.inspect = function(depth) {
return '{' + this.name + '}';
};
util.inspect(obj);
// "{nate}"</code></pre>
<h2>util.isArray(object)<span><a class="mark" href="#all_util_isarray_object" id="all_util_isarray_object">#</a></span></h2>
<p>Returns <code>true</code> if the given "object" is an <code>Array</code>. <code>false</code> otherwise.
</p>
<pre><code>var util = require('util');
util.isArray([])
// true
util.isArray(new Array)
// true
util.isArray({})
// false</code></pre>
<h2>util.isRegExp(object)<span><a class="mark" href="#all_util_isregexp_object" id="all_util_isregexp_object">#</a></span></h2>
<p>Returns <code>true</code> if the given "object" is a <code>RegExp</code>. <code>false</code> otherwise.
</p>
<pre><code>var util = require('util');
util.isRegExp(/some regexp/)
// true
util.isRegExp(new RegExp('another regexp'))
// true
util.isRegExp({})
// false</code></pre>
<h2>util.isDate(object)<span><a class="mark" href="#all_util_isdate_object" id="all_util_isdate_object">#</a></span></h2>
<p>Returns <code>true</code> if the given "object" is a <code>Date</code>. <code>false</code> otherwise.
</p>
<pre><code>var 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="#all_util_iserror_object" id="all_util_iserror_object">#</a></span></h2>
<p>Returns <code>true</code> if the given "object" is an <code>Error</code>. <code>false</code> otherwise.
</p>
<pre><code>var 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.pump(readableStream, writableStream, [callback])<span><a class="mark" href="#all_util_pump_readablestream_writablestream_callback" id="all_util_pump_readablestream_writablestream_callback">#</a></span></h2>
<pre class="api_stability_0">Stability: 0 - Deprecated: Use readableStream.pipe(writableStream)</pre><p>Read the data from <code>readableStream</code> and send it to the <code>writableStream</code>.
When <code>writableStream.write(data)</code> returns <code>false</code> <code>readableStream</code> will be
paused until the <code>drain</code> event occurs on the <code>writableStream</code>. <code>callback</code> gets
an error as its only argument and is called when <code>writableStream</code> is closed or
when an error occurs.
</p>
<h2>util.inherits(constructor, superConstructor)<span><a class="mark" href="#all_util_inherits_constructor_superconstructor" id="all_util_inherits_constructor_superconstructor">#</a></span></h2>
<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>var util = require("util");
var events = require("events");
function MyStream() {
events.EventEmitter.call(this);
}
util.inherits(MyStream, events.EventEmitter);
MyStream.prototype.write = function(data) {
this.emit("data", data);
}
var stream = new MyStream();
console.log(stream instanceof events.EventEmitter); // true
console.log(MyStream.super_ === events.EventEmitter); // true
stream.on("data", function(data) {
console.log('Received data: "' + data + '"');
})
stream.write("It works!"); // Received data: "It works!"</code></pre>
<h1>Events<span><a class="mark" href="#all_events" id="all_events">#</a></span></h1>
<pre class="api_stability_4">Stability: 4 - API Frozen</pre><!--type=module-->
<p>Many objects in Node emit events: a <code>net.Server</code> emits an event each time
a peer connects to it, a <code>fs.readStream</code> emits an event when the file is
opened. All objects which emit events are instances of <code>events.EventEmitter</code>.
You can access this module by doing: <code>require("events");</code>
</p>
<p>Typically, event names are represented by a camel-cased string, however,
there aren't any strict restrictions on that, as any string will be accepted.
</p>
<p>Functions can then be attached to objects, to be executed when an event
is emitted. These functions are called <em>listeners</em>. Inside a listener
function, <code>this</code> refers to the <code>EventEmitter</code> that the listener was
attached to.
</p>
<h2>Class: events.EventEmitter<span><a class="mark" href="#all_class_events_eventemitter" id="all_class_events_eventemitter">#</a></span></h2>
<p>To access the EventEmitter class, <code>require('events').EventEmitter</code>.
</p>
<p>When an <code>EventEmitter</code> instance experiences an error, the typical action is
to emit an <code>'error'</code> event. Error events are treated as a special case in node.
If there is no listener for it, then the default action is to print a stack
trace and exit the program.
</p>
<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>emitter.addListener(event, listener)<span><a class="mark" href="#all_emitter_addlistener_event_listener" id="all_emitter_addlistener_event_listener">#</a></span></h3>
<h3>emitter.on(event, listener)<span><a class="mark" href="#all_emitter_on_event_listener" id="all_emitter_on_event_listener">#</a></span></h3>
<p>Adds a listener to the end of the listeners array for the specified event.
</p>
<pre><code>server.on('connection', function (stream) {
console.log('someone connected!');
});</code></pre>
<p>Returns emitter, so calls can be chained.
</p>
<h3>emitter.once(event, listener)<span><a class="mark" href="#all_emitter_once_event_listener" id="all_emitter_once_event_listener">#</a></span></h3>
<p>Adds a <strong>one time</strong> listener for the event. This listener is
invoked only the next time the event is fired, after which
it is removed.
</p>
<pre><code>server.once('connection', function (stream) {
console.log('Ah, we have our first user!');
});</code></pre>
<p>Returns emitter, so calls can be chained.
</p>
<h3>emitter.removeListener(event, listener)<span><a class="mark" href="#all_emitter_removelistener_event_listener" id="all_emitter_removelistener_event_listener">#</a></span></h3>
<p>Remove a listener from the listener array for the specified event.
<strong>Caution</strong>: changes array indices in the listener array behind the listener.
</p>
<pre><code>var callback = function(stream) {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);</code></pre>
<p>Returns emitter, so calls can be chained.
</p>
<h3>emitter.removeAllListeners([event])<span><a class="mark" href="#all_emitter_removealllisteners_event" id="all_emitter_removealllisteners_event">#</a></span></h3>
<p>Removes all listeners, or those of the specified event. It's not a good idea to
remove listeners that were added elsewhere in the code, especially when it's on
an emitter that you didn't create (e.g. sockets or file streams).
</p>
<p>Returns emitter, so calls can be chained.
</p>
<h3>emitter.setMaxListeners(n)<span><a class="mark" href="#all_emitter_setmaxlisteners_n" id="all_emitter_setmaxlisteners_n">#</a></span></h3>
<p>By default EventEmitters will print a warning if more than 10 listeners are
added for a particular event. This is a useful default which helps finding memory leaks.
Obviously not all Emitters should be limited to 10. This function allows
that to be increased. Set to zero for unlimited.
</p>
<h3>emitter.listeners(event)<span><a class="mark" href="#all_emitter_listeners_event" id="all_emitter_listeners_event">#</a></span></h3>
<p>Returns an array of listeners for the specified event.
</p>
<pre><code>server.on('connection', function (stream) {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection'))); // [ [Function] ]</code></pre>
<h3>emitter.emit(event, [arg1], [arg2], [...])<span><a class="mark" href="#all_emitter_emit_event_arg1_arg2" id="all_emitter_emit_event_arg1_arg2">#</a></span></h3>
<p>Execute each of the listeners in order with the supplied arguments.
</p>
<p>Returns <code>true</code> if event had listeners, <code>false</code> otherwise.
</p>
<h3>Class Method: EventEmitter.listenerCount(emitter, event)<span><a class="mark" href="#all_class_method_eventemitter_listenercount_emitter_event" id="all_class_method_eventemitter_listenercount_emitter_event">#</a></span></h3>
<p>Return the number of listeners for a given event.
</p>
<h3>Event: 'newListener'<span><a class="mark" href="#all_event_newlistener" id="all_event_newlistener">#</a></span></h3>
<div class="signature"><ul>
<li><code>event</code> <span class="type">String</span> The event name</li>
<li><code>listener</code> <span class="type">Function</span> The event handler function</li>
</div></ul>
<p>This event is emitted any time someone adds a new listener. It is unspecified
if <code>listener</code> is in the list returned by <code>emitter.listeners(event)</code>.
</p>
<h3>Event: 'removeListener'<span><a class="mark" href="#all_event_removelistener" id="all_event_removelistener">#</a></span></h3>
<div class="signature"><ul>
<li><code>event</code> <span class="type">String</span> The event name</li>
<li><code>listener</code> <span class="type">Function</span> The event handler function</li>
</div></ul>
<p>This event is emitted any time someone removes a listener. It is unspecified
if <code>listener</code> is in the list returned by <code>emitter.listeners(event)</code>.
</p>
<h1>Domain<span><a class="mark" href="#all_domain" id="all_domain">#</a></span></h1>
<pre class="api_stability_2">Stability: 2 - Unstable</pre><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="#all_warning_don_t_ignore_errors" id="all_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 <code>throw</code> 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 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 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="javascript">// XXX WARNING! BAD IDEA!
var d = require('domain').create();
d.on('error', function(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(function() {
require('http').createServer(function(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="javascript">// Much better!
var cluster = require('cluster');
var 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', function(worker) {
console.error('disconnect!');
cluster.fork();
});
} else {
// the worker
//
// This is where we put our bugs!
var domain = require('domain');
// See the cluster documentation for more details about using
// worker processes to serve requests. How it works, caveats, etc.
var server = require('http').createServer(function(req, res) {
var d = domain.create();
d.on('error', function(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
var killtimer = setTimeout(function() {
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(function() {
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(function() {
// Whoops!
flerb.bark();
});
break;
default:
res.end('ok');
}
}</code></pre>
<h2>Additions to Error objects<span><a class="mark" href="#all_additions_to_error_objects" id="all_additions_to_error_objects">#</a></span></h2>
<!-- type=misc -->
<p>Any time an Error 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 'error' 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="#all_implicit_binding" id="all_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 <code>domain.dispose()</code> 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="#all_explicit_binding" id="all_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>// create a top-level domain for the server
var serverDomain = domain.create();
serverDomain.run(function() {
// server is created in the scope of serverDomain
http.createServer(function(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.
var reqd = domain.create();
reqd.add(req);
reqd.add(res);
reqd.on('error', function(er) {
console.error('Error', er, req.url);
try {
res.writeHead(500);
res.end('Error occurred, sorry.');
} catch (er) {
console.error('Error sending 500', er, req.url);
}
});
}).listen(1337);
});</code></pre>
<h2>domain.create()<span><a class="mark" href="#all_domain_create" id="all_domain_create">#</a></span></h2>
<div class="signature"><ul>
<li>return: <span class="type">Domain</span></li>
</div></ul>
<p>Returns a new Domain object.
</p>
<h2>Class: Domain<span><a class="mark" href="#all_class_domain" id="all_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_events_eventemitter">EventEmitter</a>. To handle the errors that it
catches, listen to its <code>error</code> event.
</p>
<h3>domain.run(fn)<span><a class="mark" href="#all_domain_run_fn" id="all_domain_run_fn">#</a></span></h3>
<div class="signature"><ul>
<li><code>fn</code> <span class="type">Function</span></li>
</div></ul>
<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.
</p>
<p>This is the most basic way to use a domain.
</p>
<p>Example:
</p>
<pre><code>var d = domain.create();
d.on('error', function(er) {
console.error('Caught error!', er);
});
d.run(function() {
process.nextTick(function() {
setTimeout(function() { // simulating some various async stuff
fs.open('non-existent file', 'r', function(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="#all_domain_members" id="all_domain_members">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">Array</span></li>
</div></ul>
<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="#all_domain_add_emitter" id="all_domain_add_emitter">#</a></span></h3>
<div class="signature"><ul>
<li><code>emitter</code> <span class="type">EventEmitter | Timer</span> emitter or timer to be added to the domain</li>
</div></ul>
<p>Explicitly adds an emitter to the domain. If any event handlers called by
the emitter throw an error, or if the emitter emits an <code>error</code> event, it
will be routed to the domain's <code>error</code> event, just like with implicit
binding.
</p>
<p>This also works with timers that are returned from <code>setInterval</code> and
<code>setTimeout</code>. 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="#all_domain_remove_emitter" id="all_domain_remove_emitter">#</a></span></h3>
<div class="signature"><ul>
<li><code>emitter</code> <span class="type">EventEmitter | Timer</span> emitter or timer to be removed from the domain</li>
</div></ul>
<p>The opposite of <code>domain.add(emitter)</code>. Removes domain handling from the
specified emitter.
</p>
<h3>domain.bind(callback)<span><a class="mark" href="#all_domain_bind_callback" id="all_domain_bind_callback">#</a></span></h3>
<div class="signature"><ul>
<li><code>callback</code> <span class="type">Function</span> The callback function</li>
<li>return: <span class="type">Function</span> The bound function</li>
</div></ul>
<p>The returned function will be a wrapper around the supplied callback
function. When the returned function is called, any errors that are
thrown will be routed to the domain's <code>error</code> event.
</p>
<h4>Example<span><a class="mark" href="#all_example" id="all_example">#</a></span></h4>
<pre><code>var d = domain.create();
function readSomeFile(filename, cb) {
fs.readFile(filename, 'utf8', d.bind(function(er, data) {
// if this throws, it will also be passed to the domain
return cb(er, data ? JSON.parse(data) : null);
}));
}
d.on('error', function(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="#all_domain_intercept_callback" id="all_domain_intercept_callback">#</a></span></h3>
<div class="signature"><ul>
<li><code>callback</code> <span class="type">Function</span> The callback function</li>
<li>return: <span class="type">Function</span> The intercepted function</li>
</div></ul>
<p>This method is almost identical to <code>domain.bind(callback)</code>. However, in
addition to catching thrown errors, it will also intercept <code>Error</code>
objects sent as the first argument to the function.
</p>
<p>In this way, the common <code>if (er) return callback(er);</code> pattern can be replaced
with a single error handler in a single place.
</p>
<h4>Example<span><a class="mark" href="#all_example_1" id="all_example_1">#</a></span></h4>
<pre><code>var d = domain.create();
function readSomeFile(filename, cb) {
fs.readFile(filename, 'utf8', d.intercept(function(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', function(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="#all_domain_enter" id="all_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 <code>domain.exit()</code> 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="#all_domain_exit" id="all_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="#all_domain_dispose" id="all_domain_dispose">#</a></span></h3>
<p>The dispose method destroys a domain, and makes a best effort attempt to
clean up any and all IO that is associated with the domain. Streams are
aborted, ended, closed, and/or destroyed. Timers are cleared.
Explicitly bound callbacks are no longer called. Any error events that
are raised as a result of this are ignored.
</p>
<p>The intention of calling <code>dispose</code> is generally to prevent cascading
errors when a critical part of the Domain context is found to be in an
error state.
</p>
<p>Once the domain is disposed the <code>dispose</code> event will emit.
</p>
<p>Note that IO might still be performed. However, to the highest degree
possible, once a domain is disposed, further errors from the emitters in
that set will be ignored. So, even if some remaining actions are still
in flight, Node.js will not communicate further about them.
</p>
<h1>Buffer<span><a class="mark" href="#all_buffer" id="all_buffer">#</a></span></h1>
<pre class="api_stability_3">Stability: 3 - Stable</pre><p>Pure JavaScript is Unicode friendly but not nice to binary data. When
dealing with TCP streams or the file system, it's necessary to handle octet
streams. Node has several strategies for manipulating, creating, and
consuming octet streams.
</p>
<p>Raw data is stored in instances of the <code>Buffer</code> class. A <code>Buffer</code> is similar
to an array of integers but corresponds to a raw memory allocation outside
the V8 heap. A <code>Buffer</code> cannot be resized.
</p>
<p>The <code>Buffer</code> class is a global, making it very rare that one would need
to ever <code>require('buffer')</code>.
</p>
<p>Converting between Buffers and JavaScript string objects requires an explicit
encoding method. Here are the different string encodings.
</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>
<p>Note that when converting from string to buffer, this encoding converts a null
character (<code>'\0'</code> or <code>'\u0000'</code>) into <code>0x20</code> (character code of a space). If
you want to convert a null character into <code>0x00</code>, you should use <code>'utf8'</code>.</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.</p>
</li>
<li><p><code>'binary'</code> - A way of encoding raw binary data into strings by using only
the first 8 bits of each character. This encoding method is deprecated and
should be avoided in favor of <code>Buffer</code> objects where possible. This encoding
will be removed in future versions of Node.</p>
</li>
<li><p><code>'hex'</code> - Encode each byte as two hexadecimal characters.</p>
</li>
</ul>
<p>A <code>Buffer</code> object can also be used with typed arrays. The buffer object is
cloned to an <code>ArrayBuffer</code> that is used as the backing store for the typed
array. The memory of the buffer and the <code>ArrayBuffer</code> is not shared.
</p>
<p>NOTE: Node.js v0.8 simply retained a reference to the buffer in <code>array.buffer</code>
instead of cloning it.
</p>
<p>While more efficient, it introduces subtle incompatibilities with the typed
arrays specification. <code>ArrayBuffer#slice()</code> makes a copy of the slice while
<code>Buffer#slice()</code> creates a view.
</p>
<h2>Class: Buffer<span><a class="mark" href="#all_class_buffer_1" id="all_class_buffer_1">#</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(size)<span><a class="mark" href="#all_new_buffer_size" id="all_new_buffer_size">#</a></span></h3>
<div class="signature"><ul>
<li><code>size</code> Number</li>
</div></ul>
<p>Allocates a new buffer of <code>size</code> octets.
</p>
<h3>new Buffer(array)<span><a class="mark" href="#all_new_buffer_array" id="all_new_buffer_array">#</a></span></h3>
<div class="signature"><ul>
<li><code>array</code> Array</li>
</div></ul>
<p>Allocates a new buffer using an <code>array</code> of octets.
</p>
<h3>new Buffer(str, [encoding])<span><a class="mark" href="#all_new_buffer_str_encoding" id="all_new_buffer_str_encoding">#</a></span></h3>
<div class="signature"><ul>
<li><code>str</code> String - string to encode.</li>
<li><code>encoding</code> String - encoding to use, Optional.</li>
</div></ul>
<p>Allocates a new buffer containing the given <code>str</code>.
<code>encoding</code> defaults to <code>'utf8'</code>.
</p>
<h3>Class Method: Buffer.isEncoding(encoding)<span><a class="mark" href="#all_class_method_buffer_isencoding_encoding" id="all_class_method_buffer_isencoding_encoding">#</a></span></h3>
<div class="signature"><ul>
<li><code>encoding</code> <span class="type">String</span> The encoding string to test</li>
</div></ul>
<p>Returns true if the <code>encoding</code> is a valid encoding argument, or false
otherwise.
</p>
<h3>buf.write(string, [offset], [length], [encoding])<span><a class="mark" href="#all_buf_write_string_offset_length_encoding" id="all_buf_write_string_offset_length_encoding">#</a></span></h3>
<div class="signature"><ul>
<li><code>string</code> String - data to be written to buffer</li>
<li><code>offset</code> Number, Optional, Default: 0</li>
<li><code>length</code> Number, Optional, Default: <code>buffer.length - offset</code></li>
<li><code>encoding</code> String, Optional, Default: 'utf8'</li>
</div></ul>
<p>Writes <code>string</code> to the buffer at <code>offset</code> using the given encoding.
<code>offset</code> defaults to <code>0</code>, <code>encoding</code> defaults to <code>'utf8'</code>. <code>length</code> is
the number of bytes to write. Returns number of octets written. If <code>buffer</code> did
not contain enough space to fit the entire string, it will write a partial
amount of the string. <code>length</code> defaults to <code>buffer.length - offset</code>.
The method will not write partial characters.
</p>
<pre><code>buf = new Buffer(256);
len = buf.write('\u00bd + \u00bc = \u00be', 0);
console.log(len + " bytes: " + buf.toString('utf8', 0, len));</code></pre>
<p>The number of characters written (which may be different than the number of
bytes written) is set in <code>Buffer._charsWritten</code> and will be overwritten the
next time <code>buf.write()</code> is called.
</p>
<h3>buf.toString([encoding], [start], [end])<span><a class="mark" href="#all_buf_tostring_encoding_start_end" id="all_buf_tostring_encoding_start_end">#</a></span></h3>
<div class="signature"><ul>
<li><code>encoding</code> String, Optional, Default: 'utf8'</li>
<li><code>start</code> Number, Optional, Default: 0</li>
<li><code>end</code> Number, Optional, Default: <code>buffer.length</code></li>
</div></ul>
<p>Decodes and returns a string from buffer data encoded with <code>encoding</code>
(defaults to <code>'utf8'</code>) beginning at <code>start</code> (defaults to <code>0</code>) and ending at
<code>end</code> (defaults to <code>buffer.length</code>).
</p>
<p>See <code>buffer.write()</code> example, above.
</p>
<h3>buf.toJSON()<span><a class="mark" href="#all_buf_tojson" id="all_buf_tojson">#</a></span></h3>
<p>Returns a JSON-representation of the Buffer instance, which is identical to the
output for JSON Arrays. <code>JSON.stringify</code> implicitly calls this function when
stringifying a Buffer instance.
</p>
<p>Example:
</p>
<pre><code>var buf = new Buffer('test');
var json = JSON.stringify(buf);
console.log(json);
// '[116,101,115,116]'
var copy = new Buffer(JSON.parse(json));
console.log(copy);
// <Buffer 74 65 73 74></code></pre>
<h3>buf[index]<span><a class="mark" href="#all_buf_index" id="all_buf_index">#</a></span></h3>
<!--type=property-->
<!--name=[index]-->
<p>Get and set the octet at <code>index</code>. The values refer to individual bytes,
so the legal range is between <code>0x00</code> and <code>0xFF</code> hex or <code>0</code> and <code>255</code>.
</p>
<p>Example: copy an ASCII string into a buffer, one byte at a time:
</p>
<pre><code>str = "node.js";
buf = new Buffer(str.length);
for (var i = 0; i < str.length ; i++) {
buf[i] = str.charCodeAt(i);
}
console.log(buf);
// node.js</code></pre>
<h3>Class Method: Buffer.isBuffer(obj)<span><a class="mark" href="#all_class_method_buffer_isbuffer_obj" id="all_class_method_buffer_isbuffer_obj">#</a></span></h3>
<div class="signature"><ul>
<li><code>obj</code> Object</li>
<li>Return: Boolean</li>
</div></ul>
<p>Tests if <code>obj</code> is a <code>Buffer</code>.
</p>
<h3>Class Method: Buffer.byteLength(string, [encoding])<span><a class="mark" href="#all_class_method_buffer_bytelength_string_encoding" id="all_class_method_buffer_bytelength_string_encoding">#</a></span></h3>
<div class="signature"><ul>
<li><code>string</code> String</li>
<li><code>encoding</code> String, Optional, Default: 'utf8'</li>
<li>Return: Number</li>
</div></ul>
<p>Gives the actual byte length of a string. <code>encoding</code> defaults to <code>'utf8'</code>.
This is not the same as <code>String.prototype.length</code> since that returns the
number of <em>characters</em> in a string.
</p>
<p>Example:
</p>
<pre><code>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.concat(list, [totalLength])<span><a class="mark" href="#all_class_method_buffer_concat_list_totallength" id="all_class_method_buffer_concat_list_totallength">#</a></span></h3>
<div class="signature"><ul>
<li><code>list</code> <span class="type">Array</span> List of Buffer objects to concat</li>
<li><code>totalLength</code> <span class="type">Number</span> Total length of the buffers when concatenated</li>
</div></ul>
<p>Returns a buffer which is the result of concatenating all the buffers in
the list together.
</p>
<p>If the list has no items, or if the totalLength is 0, then it returns a
zero-length buffer.
</p>
<p>If the list has exactly one item, then the first item of the list is
returned.
</p>
<p>If the list has more than one item, then a new Buffer is created.
</p>
<p>If totalLength is not provided, it is read from the buffers in the list.
However, this adds an additional loop to the function, so it is faster
to provide the length explicitly.
</p>
<h3>buf.length<span><a class="mark" href="#all_buf_length" id="all_buf_length">#</a></span></h3>
<div class="signature"><ul>
<li>Number</li>
</div></ul>
<p>The size of the buffer in bytes. Note that this is not necessarily the size
of the contents. <code>length</code> refers to the amount of memory allocated for the
buffer object. It does not change when the contents of the buffer are changed.
</p>
<pre><code>buf = new Buffer(1234);
console.log(buf.length);
buf.write("some string", 0, "ascii");
console.log(buf.length);
// 1234
// 1234</code></pre>
<h3>buf.copy(targetBuffer, [targetStart], [sourceStart], [sourceEnd])<span><a class="mark" href="#all_buf_copy_targetbuffer_targetstart_sourcestart_sourceend" id="all_buf_copy_targetbuffer_targetstart_sourcestart_sourceend">#</a></span></h3>
<div class="signature"><ul>
<li><code>targetBuffer</code> Buffer object - Buffer to copy into</li>
<li><code>targetStart</code> Number, Optional, Default: 0</li>
<li><code>sourceStart</code> Number, Optional, Default: 0</li>
<li><code>sourceEnd</code> Number, Optional, Default: <code>buffer.length</code></li>
</div></ul>
<p>Does copy between buffers. The source and target regions can be overlapped.
<code>targetStart</code> and <code>sourceStart</code> default to <code>0</code>.
<code>sourceEnd</code> defaults to <code>buffer.length</code>.
</p>
<p>All values passed that are <code>undefined</code>/<code>NaN</code> or are out of bounds are set equal
to their respective defaults.
</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>buf1 = new Buffer(26);
buf2 = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
buf1[i] = i + 97; // 97 is ASCII a
buf2[i] = 33; // ASCII !
}
buf1.copy(buf2, 8, 16, 20);
console.log(buf2.toString('ascii', 0, 25));
// !!!!!!!!qrst!!!!!!!!!!!!!</code></pre>
<h3>buf.slice([start], [end])<span><a class="mark" href="#all_buf_slice_start_end" id="all_buf_slice_start_end">#</a></span></h3>
<div class="signature"><ul>
<li><code>start</code> Number, Optional, Default: 0</li>
<li><code>end</code> Number, Optional, Default: <code>buffer.length</code></li>
</div></ul>
<p>Returns a new buffer which references the same memory as the old, but offset
and cropped by the <code>start</code> (defaults to <code>0</code>) and <code>end</code> (defaults to
<code>buffer.length</code>) indexes. Negative indexes start from the end of the buffer.
</p>
<p><strong>Modifying the new buffer slice will modify memory in the original buffer!</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>var buf1 = new Buffer(26);
for (var i = 0 ; i < 26 ; i++) {
buf1[i] = i + 97; // 97 is ASCII a
}
var buf2 = buf1.slice(0, 3);
console.log(buf2.toString('ascii', 0, buf2.length));
buf1[0] = 33;
console.log(buf2.toString('ascii', 0, buf2.length));
// abc
// !bc</code></pre>
<h3>buf.readUInt8(offset, [noAssert])<span><a class="mark" href="#all_buf_readuint8_offset_noassert" id="all_buf_readuint8_offset_noassert">#</a></span></h3>
<div class="signature"><ul>
<li><code>offset</code> Number</li>
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
<li>Return: Number</li>
</div></ul>
<p>Reads an unsigned 8 bit integer from the buffer at the specified offset.
</p>
<p>Set <code>noAssert</code> to true to skip validation of <code>offset</code>. This means that <code>offset</code>
may be beyond the end of the buffer. Defaults to <code>false</code>.
</p>
<p>Example:
</p>
<pre><code>var buf = new Buffer(4);
buf[0] = 0x3;
buf[1] = 0x4;
buf[2] = 0x23;
buf[3] = 0x42;
for (ii = 0; ii < buf.length; ii++) {
console.log(buf.readUInt8(ii));
}
// 0x3
// 0x4
// 0x23
// 0x42</code></pre>
<h3>buf.readUInt16LE(offset, [noAssert])<span><a class="mark" href="#all_buf_readuint16le_offset_noassert" id="all_buf_readuint16le_offset_noassert">#</a></span></h3>
<h3>buf.readUInt16BE(offset, [noAssert])<span><a class="mark" href="#all_buf_readuint16be_offset_noassert" id="all_buf_readuint16be_offset_noassert">#</a></span></h3>
<ul>
<li><code>offset</code> Number</li>
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
<li>Return: Number</li>
</ul>
<p>Reads an unsigned 16 bit integer from the buffer at the specified offset with
specified endian format.
</p>
<p>Set <code>noAssert</code> to true to skip validation of <code>offset</code>. This means that <code>offset</code>
may be beyond the end of the buffer. Defaults to <code>false</code>.
</p>
<p>Example:
</p>
<pre><code>var buf = new Buffer(4);
buf[0] = 0x3;
buf[1] = 0x4;
buf[2] = 0x23;
buf[3] = 0x42;
console.log(buf.readUInt16BE(0));
console.log(buf.readUInt16LE(0));
console.log(buf.readUInt16BE(1));
console.log(buf.readUInt16LE(1));
console.log(buf.readUInt16BE(2));
console.log(buf.readUInt16LE(2));
// 0x0304
// 0x0403
// 0x0423
// 0x2304
// 0x2342
// 0x4223</code></pre>
<h3>buf.readUInt32LE(offset, [noAssert])<span><a class="mark" href="#all_buf_readuint32le_offset_noassert" id="all_buf_readuint32le_offset_noassert">#</a></span></h3>
<h3>buf.readUInt32BE(offset, [noAssert])<span><a class="mark" href="#all_buf_readuint32be_offset_noassert" id="all_buf_readuint32be_offset_noassert">#</a></span></h3>
<ul>
<li><code>offset</code> Number</li>
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
<li>Return: Number</li>
</ul>
<p>Reads an unsigned 32 bit integer from the buffer at the specified offset with
specified endian format.
</p>
<p>Set <code>noAssert</code> to true to skip validation of <code>offset</code>. This means that <code>offset</code>
may be beyond the end of the buffer. Defaults to <code>false</code>.
</p>
<p>Example:
</p>
<pre><code>var buf = new Buffer(4);
buf[0] = 0x3;
buf[1] = 0x4;
buf[2] = 0x23;
buf[3] = 0x42;
console.log(buf.readUInt32BE(0));
console.log(buf.readUInt32LE(0));
// 0x03042342
// 0x42230403</code></pre>
<h3>buf.readInt8(offset, [noAssert])<span><a class="mark" href="#all_buf_readint8_offset_noassert" id="all_buf_readint8_offset_noassert">#</a></span></h3>
<div class="signature"><ul>
<li><code>offset</code> Number</li>
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
<li>Return: Number</li>
</div></ul>
<p>Reads a signed 8 bit integer from the buffer at the specified offset.
</p>
<p>Set <code>noAssert</code> to true to skip validation of <code>offset</code>. This means that <code>offset</code>
may be beyond the end of the buffer. Defaults to <code>false</code>.
</p>
<p>Works as <code>buffer.readUInt8</code>, except buffer contents are treated as two's
complement signed values.
</p>
<h3>buf.readInt16LE(offset, [noAssert])<span><a class="mark" href="#all_buf_readint16le_offset_noassert" id="all_buf_readint16le_offset_noassert">#</a></span></h3>
<h3>buf.readInt16BE(offset, [noAssert])<span><a class="mark" href="#all_buf_readint16be_offset_noassert" id="all_buf_readint16be_offset_noassert">#</a></span></h3>
<ul>
<li><code>offset</code> Number</li>
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
<li>Return: Number</li>
</ul>
<p>Reads a signed 16 bit integer from the buffer at the specified offset with
specified endian format.
</p>
<p>Set <code>noAssert</code> to true to skip validation of <code>offset</code>. This means that <code>offset</code>
may be beyond the end of the buffer. Defaults to <code>false</code>.
</p>
<p>Works as <code>buffer.readUInt16*</code>, except buffer contents are treated as two's
complement signed values.
</p>
<h3>buf.readInt32LE(offset, [noAssert])<span><a class="mark" href="#all_buf_readint32le_offset_noassert" id="all_buf_readint32le_offset_noassert">#</a></span></h3>
<h3>buf.readInt32BE(offset, [noAssert])<span><a class="mark" href="#all_buf_readint32be_offset_noassert" id="all_buf_readint32be_offset_noassert">#</a></span></h3>
<ul>
<li><code>offset</code> Number</li>
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
<li>Return: Number</li>
</ul>
<p>Reads a signed 32 bit integer from the buffer at the specified offset with
specified endian format.
</p>
<p>Set <code>noAssert</code> to true to skip validation of <code>offset</code>. This means that <code>offset</code>
may be beyond the end of the buffer. Defaults to <code>false</code>.
</p>
<p>Works as <code>buffer.readUInt32*</code>, except buffer contents are treated as two's
complement signed values.
</p>
<h3>buf.readFloatLE(offset, [noAssert])<span><a class="mark" href="#all_buf_readfloatle_offset_noassert" id="all_buf_readfloatle_offset_noassert">#</a></span></h3>
<h3>buf.readFloatBE(offset, [noAssert])<span><a class="mark" href="#all_buf_readfloatbe_offset_noassert" id="all_buf_readfloatbe_offset_noassert">#</a></span></h3>
<ul>
<li><code>offset</code> Number</li>
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
<li>Return: Number</li>
</ul>
<p>Reads a 32 bit float from the buffer at the specified offset with specified
endian format.
</p>
<p>Set <code>noAssert</code> to true to skip validation of <code>offset</code>. This means that <code>offset</code>
may be beyond the end of the buffer. Defaults to <code>false</code>.
</p>
<p>Example:
</p>
<pre><code>var buf = new Buffer(4);
buf[0] = 0x00;
buf[1] = 0x00;
buf[2] = 0x80;
buf[3] = 0x3f;
console.log(buf.readFloatLE(0));
// 0x01</code></pre>
<h3>buf.readDoubleLE(offset, [noAssert])<span><a class="mark" href="#all_buf_readdoublele_offset_noassert" id="all_buf_readdoublele_offset_noassert">#</a></span></h3>
<h3>buf.readDoubleBE(offset, [noAssert])<span><a class="mark" href="#all_buf_readdoublebe_offset_noassert" id="all_buf_readdoublebe_offset_noassert">#</a></span></h3>
<ul>
<li><code>offset</code> Number</li>
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
<li>Return: Number</li>
</ul>
<p>Reads a 64 bit double from the buffer at the specified offset with specified
endian format.
</p>
<p>Set <code>noAssert</code> to true to skip validation of <code>offset</code>. This means that <code>offset</code>
may be beyond the end of the buffer. Defaults to <code>false</code>.
</p>
<p>Example:
</p>
<pre><code>var buf = new Buffer(8);
buf[0] = 0x55;
buf[1] = 0x55;
buf[2] = 0x55;
buf[3] = 0x55;
buf[4] = 0x55;
buf[5] = 0x55;
buf[6] = 0xd5;
buf[7] = 0x3f;
console.log(buf.readDoubleLE(0));
// 0.3333333333333333</code></pre>
<h3>buf.writeUInt8(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writeuint8_value_offset_noassert" id="all_buf_writeuint8_value_offset_noassert">#</a></span></h3>
<div class="signature"><ul>
<li><code>value</code> Number</li>
<li><code>offset</code> Number</li>
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
</div></ul>
<p>Writes <code>value</code> to the buffer at the specified offset. Note, <code>value</code> must be a
valid 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. Defaults to <code>false</code>.
</p>
<p>Example:
</p>
<pre><code>var buf = new Buffer(4);
buf.writeUInt8(0x3, 0);
buf.writeUInt8(0x4, 1);
buf.writeUInt8(0x23, 2);
buf.writeUInt8(0x42, 3);
console.log(buf);
// <Buffer 03 04 23 42></code></pre>
<h3>buf.writeUInt16LE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writeuint16le_value_offset_noassert" id="all_buf_writeuint16le_value_offset_noassert">#</a></span></h3>
<h3>buf.writeUInt16BE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writeuint16be_value_offset_noassert" id="all_buf_writeuint16be_value_offset_noassert">#</a></span></h3>
<ul>
<li><code>value</code> Number</li>
<li><code>offset</code> Number</li>
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
</ul>
<p>Writes <code>value</code> to the buffer at the specified offset with specified endian
format. Note, <code>value</code> must be a valid 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. Defaults to <code>false</code>.
</p>
<p>Example:
</p>
<pre><code>var buf = new Buffer(4);
buf.writeUInt16BE(0xdead, 0);
buf.writeUInt16BE(0xbeef, 2);
console.log(buf);
buf.writeUInt16LE(0xdead, 0);
buf.writeUInt16LE(0xbeef, 2);
console.log(buf);
// <Buffer de ad be ef>
// <Buffer ad de ef be></code></pre>
<h3>buf.writeUInt32LE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writeuint32le_value_offset_noassert" id="all_buf_writeuint32le_value_offset_noassert">#</a></span></h3>
<h3>buf.writeUInt32BE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writeuint32be_value_offset_noassert" id="all_buf_writeuint32be_value_offset_noassert">#</a></span></h3>
<ul>
<li><code>value</code> Number</li>
<li><code>offset</code> Number</li>
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
</ul>
<p>Writes <code>value</code> to the buffer at the specified offset with specified endian
format. Note, <code>value</code> must be a valid 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. Defaults to <code>false</code>.
</p>
<p>Example:
</p>
<pre><code>var buf = new Buffer(4);
buf.writeUInt32BE(0xfeedface, 0);
console.log(buf);
buf.writeUInt32LE(0xfeedface, 0);
console.log(buf);
// <Buffer fe ed fa ce>
// <Buffer ce fa ed fe></code></pre>
<h3>buf.writeInt8(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writeint8_value_offset_noassert" id="all_buf_writeint8_value_offset_noassert">#</a></span></h3>
<div class="signature"><ul>
<li><code>value</code> Number</li>
<li><code>offset</code> Number</li>
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
</div></ul>
<p>Writes <code>value</code> to the buffer at the specified offset. Note, <code>value</code> must be a
valid 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. Defaults to <code>false</code>.
</p>
<p>Works as <code>buffer.writeUInt8</code>, except value is written out as a two's complement
signed integer into <code>buffer</code>.
</p>
<h3>buf.writeInt16LE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writeint16le_value_offset_noassert" id="all_buf_writeint16le_value_offset_noassert">#</a></span></h3>
<h3>buf.writeInt16BE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writeint16be_value_offset_noassert" id="all_buf_writeint16be_value_offset_noassert">#</a></span></h3>
<ul>
<li><code>value</code> Number</li>
<li><code>offset</code> Number</li>
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
</ul>
<p>Writes <code>value</code> to the buffer at the specified offset with specified endian
format. Note, <code>value</code> must be a valid 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. Defaults to <code>false</code>.
</p>
<p>Works as <code>buffer.writeUInt16*</code>, except value is written out as a two's
complement signed integer into <code>buffer</code>.
</p>
<h3>buf.writeInt32LE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writeint32le_value_offset_noassert" id="all_buf_writeint32le_value_offset_noassert">#</a></span></h3>
<h3>buf.writeInt32BE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writeint32be_value_offset_noassert" id="all_buf_writeint32be_value_offset_noassert">#</a></span></h3>
<ul>
<li><code>value</code> Number</li>
<li><code>offset</code> Number</li>
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
</ul>
<p>Writes <code>value</code> to the buffer at the specified offset with specified endian
format. Note, <code>value</code> must be a valid 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. Defaults to <code>false</code>.
</p>
<p>Works as <code>buffer.writeUInt32*</code>, except value is written out as a two's
complement signed integer into <code>buffer</code>.
</p>
<h3>buf.writeFloatLE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writefloatle_value_offset_noassert" id="all_buf_writefloatle_value_offset_noassert">#</a></span></h3>
<h3>buf.writeFloatBE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writefloatbe_value_offset_noassert" id="all_buf_writefloatbe_value_offset_noassert">#</a></span></h3>
<ul>
<li><code>value</code> Number</li>
<li><code>offset</code> Number</li>
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
</ul>
<p>Writes <code>value</code> to the buffer at the specified offset with specified endian
format. Note, behavior is unspecified if <code>value</code> is not 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. Defaults to <code>false</code>.
</p>
<p>Example:
</p>
<pre><code>var buf = new Buffer(4);
buf.writeFloatBE(0xcafebabe, 0);
console.log(buf);
buf.writeFloatLE(0xcafebabe, 0);
console.log(buf);
// <Buffer 4f 4a fe bb>
// <Buffer bb fe 4a 4f></code></pre>
<h3>buf.writeDoubleLE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writedoublele_value_offset_noassert" id="all_buf_writedoublele_value_offset_noassert">#</a></span></h3>
<h3>buf.writeDoubleBE(value, offset, [noAssert])<span><a class="mark" href="#all_buf_writedoublebe_value_offset_noassert" id="all_buf_writedoublebe_value_offset_noassert">#</a></span></h3>
<ul>
<li><code>value</code> Number</li>
<li><code>offset</code> Number</li>
<li><code>noAssert</code> Boolean, Optional, Default: false</li>
</ul>
<p>Writes <code>value</code> to the buffer at the specified offset with specified endian
format. Note, <code>value</code> must be a valid 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. Defaults to <code>false</code>.
</p>
<p>Example:
</p>
<pre><code>var buf = new Buffer(8);
buf.writeDoubleBE(0xdeadbeefcafebabe, 0);
console.log(buf);
buf.writeDoubleLE(0xdeadbeefcafebabe, 0);
console.log(buf);
// <Buffer 43 eb d5 b7 dd f9 5f d7>
// <Buffer d7 5f f9 dd b7 d5 eb 43></code></pre>
<h3>buf.fill(value, [offset], [end])<span><a class="mark" href="#all_buf_fill_value_offset_end" id="all_buf_fill_value_offset_end">#</a></span></h3>
<div class="signature"><ul>
<li><code>value</code></li>
<li><code>offset</code> Number, Optional</li>
<li><code>end</code> Number, Optional</li>
</div></ul>
<p>Fills the buffer with the specified value. If the <code>offset</code> (defaults to <code>0</code>)
and <code>end</code> (defaults to <code>buffer.length</code>) are not given it will fill the entire
buffer.
</p>
<pre><code>var b = new Buffer(50);
b.fill("h");</code></pre>
<h2>buffer.INSPECT_MAX_BYTES<span><a class="mark" href="#all_buffer_inspect_max_bytes" id="all_buffer_inspect_max_bytes">#</a></span></h2>
<div class="signature"><ul>
<li>Number, Default: 50</li>
</div></ul>
<p>How many bytes will be returned when <code>buffer.inspect()</code> is called. This can
be overridden by user modules.
</p>
<p>Note that this is a property on the buffer module returned by
<code>require('buffer')</code>, not on the Buffer global, or a buffer instance.
</p>
<h2>Class: SlowBuffer<span><a class="mark" href="#all_class_slowbuffer" id="all_class_slowbuffer">#</a></span></h2>
<p>This class is primarily for internal use. JavaScript programs should
use Buffer instead of using SlowBuffer.
</p>
<p>In order to avoid the overhead of allocating many C++ Buffer objects for
small blocks of memory in the lifetime of a server, Node allocates memory
in 8Kb (8192 byte) chunks. If a buffer is smaller than this size, then it
will be backed by a parent SlowBuffer object. If it is larger than this,
then Node will allocate a SlowBuffer slab for it directly.
</p>
<h1>Stream<span><a class="mark" href="#all_stream" id="all_stream">#</a></span></h1>
<pre class="api_stability_2">Stability: 2 - Unstable</pre><p>A stream is an abstract interface implemented by various objects in
Node. For example a <a href="http.html#http_http_incomingmessage">request to an HTTP
server</a> is a stream, as is
<a href="process.html#process_process_stdout">stdout</a>. Streams are readable, writable, or both. All streams are
instances of <a href="events.html#events_class_events_eventemitter">EventEmitter</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. The first explains the
parts of the API that you need to be aware of to use streams in your
programs. If you never implement a streaming API yourself, you can
stop there.
</p>
<p>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.
</p>
<p>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.
</p>
<h2>API for Stream Consumers<span><a class="mark" href="#all_api_for_stream_consumers" id="all_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 below. 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> below.
</p>
<p>Almost all Node programs, no matter how simple, use Streams in some
way. Here is an example of using Streams in a Node program:
</p>
<pre><code class="javascript">var http = require('http');
var server = http.createServer(function (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', function (chunk) {
body += chunk;
})
// the end event tells you that you have entire body
req.on('end', function () {
try {
var data = JSON.parse(body);
} catch (er) {
// uh oh! bad json!
res.statusCode = 400;
return res.end('error: ' + er.message);
}
// write back something interesting to the user:
res.write(typeof data);
res.end();
})
})
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.Readable<span><a class="mark" href="#all_class_stream_readable" id="all_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>non-flowing
mode</strong>. When in flowing mode, data is read from the underlying system
and provided to your program as fast as possible. In non-flowing
mode, you must explicitly call <code>stream.read()</code> to get chunks of data
out.
</p>
<p>Examples of readable streams include:
</p>
<ul>
<li><a href="http.html#http_http_incomingmessage">http responses, on the client</a></li>
<li><a href="http.html#http_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">process.stdin</a></li>
</ul>
<h4>Event: 'readable'<span><a class="mark" href="#all_event_readable" id="all_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="javascript">var readable = getReadableStreamSomehow();
readable.on('readable', function() {
// 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>
<h4>Event: 'data'<span><a class="mark" href="#all_event_data" id="all_event_data">#</a></span></h4>
<div class="signature"><ul>
<li><code>chunk</code> <span class="type">Buffer | String</span> The chunk of data.</li>
</div></ul>
<p>If you attach a <code>data</code> event listener, then it will switch the stream
into flowing mode, and data will be passed to your handler 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="javascript">var readable = getReadableStreamSomehow();
readable.on('data', function(chunk) {
console.log('got %d bytes of data', chunk.length);
})</code></pre>
<h4>Event: 'end'<span><a class="mark" href="#all_event_end" id="all_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 <code>read()</code> repeatedly until you get to the end.
</p>
<pre><code class="javascript">var readable = getReadableStreamSomehow();
readable.on('data', function(chunk) {
console.log('got %d bytes of data', chunk.length);
})
readable.on('end', function() {
console.log('there will be no more data.');
});</code></pre>
<h4>Event: 'close'<span><a class="mark" href="#all_event_close" id="all_event_close">#</a></span></h4>
<p>Emitted when the underlying resource (for example, the backing file
descriptor) has been closed. Not all streams will emit this.
</p>
<h4>Event: 'error'<span><a class="mark" href="#all_event_error" id="all_event_error">#</a></span></h4>
<p>Emitted if there was an error receiving data.
</p>
<h4>readable.read([size])<span><a class="mark" href="#all_readable_read_size" id="all_readable_read_size">#</a></span></h4>
<div class="signature"><ul>
<li><code>size</code> <span class="type">Number</span> Optional argument to specify how much data to read.</li>
<li>Return <span class="type">String | Buffer | null</span></li>
</div></ul>
<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>.
</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 non-flowing mode. In
flowing-mode, this method is called automatically until the internal
buffer is drained.
</p>
<pre><code class="javascript">var readable = getReadableStreamSomehow();
readable.on('readable', function() {
var chunk;
while (null !== (chunk = readable.read())) {
console.log('got %d bytes of data', chunk.length);
}
});</code></pre>
<h4>readable.setEncoding(encoding)<span><a class="mark" href="#all_readable_setencoding_encoding" id="all_readable_setencoding_encoding">#</a></span></h4>
<div class="signature"><ul>
<li><code>encoding</code> <span class="type">String</span> The encoding to use.</li>
</div></ul>
<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 <code>buf.toString(encoding)</code> on them. If you want to read the data
as strings, always use this method.
</p>
<pre><code class="javascript">var readable = getReadableStreamSomehow();
readable.setEncoding('utf8');
readable.on('data', function(chunk) {
assert.equal(typeof chunk, 'string');
console.log('got %d characters of string data', chunk.length);
})</code></pre>
<h4>readable.resume()<span><a class="mark" href="#all_readable_resume" id="all_readable_resume">#</a></span></h4>
<p>This method will cause the readable stream to resume emitting <code>data</code>
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 <code>end</code> event, you can call <code>readable.resume()</code> to open the flow of
data.
</p>
<pre><code class="javascript">var readable = getReadableStreamSomehow();
readable.resume();
readable.on('end', function(chunk) {
console.log('got to the end, but did not read anything');
})</code></pre>
<h4>readable.pause()<span><a class="mark" href="#all_readable_pause" id="all_readable_pause">#</a></span></h4>
<p>This method will cause a stream in flowing-mode to stop emitting
<code>data</code> events. Any data that becomes available will remain in the
internal buffer.
</p>
<p>This method is only relevant in flowing mode. When called on a
non-flowing stream, it will switch into flowing mode, but remain
paused.
</p>
<pre><code class="javascript">var readable = getReadableStreamSomehow();
readable.on('data', function(chunk) {
console.log('got %d bytes of data', chunk.length);
readable.pause();
console.log('there will be no more data for 1 second');
setTimeout(function() {
console.log('now data will start flowing again');
readable.resume();
}, 1000);
})</code></pre>
<h4>readable.pipe(destination, [options])<span><a class="mark" href="#all_readable_pipe_destination_options" id="all_readable_pipe_destination_options">#</a></span></h4>
<div class="signature"><ul>
<li><code>destination</code> <span class="type"><a href="#stream_class_stream_writable">Writable</a> Stream</span> The destination for writing data</li>
<li><code>options</code> <span class="type">Object</span> Pipe options<ul>
<li><code>end</code> <span class="type">Boolean</span> End the writer when the reader ends. Default = <code>true</code></li>
</ul>
</li>
</div></ul>
<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="javascript">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="javascript">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="javascript">process.stdin.pipe(process.stdout);</code></pre>
<p>By default <a href="#stream_writable_end_chunk_encoding_callback"><code>end()</code></a> is called on the destination when the source stream
emits <code>end</code>, 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="javascript">reader.pipe(writer, { end: false });
reader.on('end', function() {
writer.end('Goodbye\n');
});</code></pre>
<p>Note that <code>process.stderr</code> and <code>process.stdout</code> are never closed until
the process exits, regardless of the specified options.
</p>
<h4>readable.unpipe([destination])<span><a class="mark" href="#all_readable_unpipe_destination" id="all_readable_unpipe_destination">#</a></span></h4>
<div class="signature"><ul>
<li><code>destination</code> <span class="type"><a href="#stream_class_stream_writable">Writable</a> Stream</span> Optional specific stream to unpipe</li>
</div></ul>
<p>This method will remove the hooks set up for a previous <code>pipe()</code> 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="javascript">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(function() {
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="#all_readable_unshift_chunk" id="all_readable_unshift_chunk">#</a></span></h4>
<div class="signature"><ul>
<li><code>chunk</code> <span class="type">Buffer | String</span> Chunk of data to unshift onto the read queue</li>
</div></ul>
<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>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 API
for Stream Implementors, below.)
</p>
<pre><code class="javascript">// Pull off a header delimited by \n\n
// use unshift() if we get too much
// Call the callback with (error, header, stream)
var 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>
<h4>readable.wrap(stream)<span><a class="mark" href="#all_readable_wrap_stream" id="all_readable_wrap_stream">#</a></span></h4>
<div class="signature"><ul>
<li><code>stream</code> <span class="type">Stream</span> An "old style" readable stream</li>
</div></ul>
<p>Versions of Node prior to v0.10 had streams that did not implement the
entire Streams API as it is today. (See "Compatibility" below for
more information.)
</p>
<p>If you are using an older Node library that emits <code>'data'</code> events and
has a <code>pause()</code> 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 programs and libraries.
</p>
<p>For example:
</p>
<pre><code class="javascript">var OldReader = require('./old-api-module.js').OldReader;
var oreader = new OldReader;
var Readable = require('stream').Readable;
var myReader = new Readable().wrap(oreader);
myReader.on('readable', function() {
myReader.read(); // etc.
});</code></pre>
<h3>Class: stream.Writable<span><a class="mark" href="#all_class_stream_writable" id="all_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">process.stdout</a>, <a href="process.html#process_process_stderr">process.stderr</a></li>
</ul>
<h4>writable.write(chunk, [encoding], [callback])<span><a class="mark" href="#all_writable_write_chunk_encoding_callback" id="all_writable_write_chunk_encoding_callback">#</a></span></h4>
<div class="signature"><ul>
<li><code>chunk</code> <span class="type">String | Buffer</span> The data to write</li>
<li><code>encoding</code> <span class="type">String</span> The encoding, if <code>chunk</code> is a String</li>
<li><code>callback</code> <span class="type">Function</span> Callback for when this chunk of data is flushed</li>
<li>Returns: <span class="type">Boolean</span> True if the data was handled completely.</li>
</div></ul>
<p>This method writes some data to the underlying system, and calls the
supplied callback once the data has been fully handled.
</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 <code>drain</code> event before writing more data.
</p>
<h4>Event: 'drain'<span><a class="mark" href="#all_event_drain" id="all_event_drain">#</a></span></h4>
<p>If a <a href="#stream_writable_write_chunk_encoding_callback"><code>writable.write(chunk)</code></a> call returns false, then the <code>drain</code>
event will indicate when it is appropriate to begin writing more data
to the stream.
</p>
<pre><code class="javascript">// Write the data to the supplied writable stream 1MM 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>writable.end([chunk], [encoding], [callback])<span><a class="mark" href="#all_writable_end_chunk_encoding_callback" id="all_writable_end_chunk_encoding_callback">#</a></span></h4>
<div class="signature"><ul>
<li><code>chunk</code> <span class="type">String | Buffer</span> Optional data to write</li>
<li><code>encoding</code> <span class="type">String</span> The encoding, if <code>chunk</code> is a String</li>
<li><code>callback</code> <span class="type">Function</span> Optional callback for when the stream is finished</li>
</div></ul>
<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 <code>finish</code> event.
</p>
<p>Calling <a href="#stream_writable_write_chunk_encoding_callback"><code>write()</code></a> after calling <a href="#stream_writable_end_chunk_encoding_callback"><code>end()</code></a> will raise an error.
</p>
<pre><code class="javascript">// write 'hello, ' and then end with 'world!'
http.createServer(function (req, res) {
res.write('hello, ');
res.end('world!');
// writing more now is not allowed!
});</code></pre>
<h4>Event: 'finish'<span><a class="mark" href="#all_event_finish" id="all_event_finish">#</a></span></h4>
<p>When the <a href="#stream_writable_end_chunk_encoding_callback"><code>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="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', function() {
console.error('all writes are now complete.');
});</code></pre>
<h4>Event: 'pipe'<span><a class="mark" href="#all_event_pipe" id="all_event_pipe">#</a></span></h4>
<div class="signature"><ul>
<li><code>src</code> <span class="type"><a href="#stream_class_stream_readable">Readable</a> Stream</span> source stream that is piping to this writable</li>
</div></ul>
<p>This is emitted whenever the <code>pipe()</code> method is called on a readable
stream, adding this writable to its set of destinations.
</p>
<pre><code class="javascript">var writer = getWritableStreamSomehow();
var reader = getReadableStreamSomehow();
writer.on('pipe', function(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="#all_event_unpipe" id="all_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>
</div></ul>
<p>This is emitted whenever the <a href="#stream_readable_unpipe_destination"><code>unpipe()</code></a> method is called on a
readable stream, removing this writable from its set of destinations.
</p>
<pre><code class="javascript">var writer = getWritableStreamSomehow();
var reader = getReadableStreamSomehow();
writer.on('unpipe', function(src) {
console.error('something has stopped piping into the writer');
assert.equal(src, reader);
});
reader.pipe(writer);
reader.unpipe(writer);</code></pre>
<h4>Event: 'error'<span><a class="mark" href="#all_event_error_1" id="all_event_error_1">#</a></span></h4>
<p>Emitted if there was an error when writing or piping data.
</p>
<h3>Class: stream.Duplex<span><a class="mark" href="#all_class_stream_duplex" id="all_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. See above for usage.
</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.Transform<span><a class="mark" href="#all_class_stream_transform" id="all_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. See above for usage.
</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>
<h2>API for Stream Implementors<span><a class="mark" href="#all_api_for_stream_implementors" id="all_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></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></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>_transform</code>, <code>_flush</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> above. Otherwise, you
can potentially cause adverse side effects in programs that consume
your streaming interfaces.
</p>
<h3>Class: stream.Readable<span><a class="mark" href="#all_class_stream_readable_1" id="all_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>_read(size)</code></a> method.
</p>
<p>Please see above under <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>Example: A Counting Stream<span><a class="mark" href="#all_example_a_counting_stream" id="all_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="javascript">var Readable = require('stream').Readable;
var 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="#all_example_simpleprotocol_v1_sub_optimal" id="all_example_simpleprotocol_v1_sub_optimal">#</a></span></h4>
<p>This is similar to the <code>parseHeader</code> function described above, 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
below for a better implementation.
</p>
<pre><code class="javascript">// 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.
var Readable = require('stream').Readable;
var 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;
var self = this;
source.on('end', function() {
self.push(null);
});
// give it a kick whenever the source is readable
// read(0) will not consume any bytes
source.on('readable', function() {
self.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);
// 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>
<h4>new stream.Readable([options])<span><a class="mark" href="#all_new_stream_readable_options" id="all_new_stream_readable_options">#</a></span></h4>
<div class="signature"><ul>
<li><code>options</code> <span class="type">Object</span><ul>
<li><code>highWaterMark</code> <span class="type">Number</span> The maximum number of bytes to store in
the internal buffer before ceasing to read from the underlying
resource. Default=16kb</li>
<li><code>encoding</code> <span class="type">String</span> If specified, then buffers will be decoded to
strings using the specified encoding. Default=null</li>
<li><code>objectMode</code> <span class="type">Boolean</span> Whether this stream should behave
as a stream of objects. Meaning that stream.read(n) returns
a single value instead of a Buffer of size n. Default=false</li>
</ul>
</li>
</div></ul>
<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="#all_readable_read_size_1" id="all_readable_read_size_1">#</a></span></h4>
<div class="signature"><ul>
<li><code>size</code> <span class="type">Number</span> Number of bytes to read asynchronously</li>
</div></ul>
<p>Note: <strong>Implement this function, but do NOT call it directly.</strong>
</p>
<p>This function should NOT be called directly. It should be implemented
by child classes, and only called by the internal Readable class
methods.
</p>
<p>All Readable stream implementations must provide a <code>_read</code> method to
fetch data from the underlying resource.
</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>
<p>When data is available, put it into the read queue by calling
<code>readable.push(chunk)</code>. If <code>push</code> returns false, then you should stop
reading. When <code>_read</code> is called again, you should start pushing more
data.
</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="#all_readable_push_chunk_encoding" id="all_readable_push_chunk_encoding">#</a></span></h4>
<div class="signature"><ul>
<li><code>chunk</code> <span class="type">Buffer | null | String</span> Chunk of data to push into the read queue</li>
<li><code>encoding</code> <span class="type">String</span> Encoding of String chunks. Must be a valid
Buffer encoding, such as <code>'utf8'</code> or <code>'ascii'</code></li>
<li>return <span class="type">Boolean</span> Whether or not more pushes should be performed</li>
</div></ul>
<p>Note: <strong>This function should be called by Readable implementors, NOT
by consumers of Readable streams.</strong>
</p>
<p>The <code>_read()</code> function will not be called again until at least one
<code>push(chunk)</code> call is made.
</p>
<p>The <code>Readable</code> class works by putting data into a read queue to be
pulled out later by calling the <code>read()</code> method when the <code>'readable'</code>
event fires.
</p>
<p>The <code>push()</code> method will explicitly insert some data into the read
queue. If it is called with <code>null</code> then it will signal the end of the
data (EOF).
</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="javascript">// 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();
var self = this;
// Every time there's data, we push it into the internal buffer.
this._source.ondata = function(chunk) {
// if push() returns false, then we need to stop reading from source
if (!self.push(chunk))
self._source.readStop();
};
// When the source ends, we push the EOF-signalling `null` chunk
this._source.onend = function() {
self.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>
<h3>Class: stream.Writable<span><a class="mark" href="#all_class_stream_writable_1" id="all_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>_write(chunk, encoding, callback)</code></a> method.
</p>
<p>Please see above under <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([options])<span><a class="mark" href="#all_new_stream_writable_options" id="all_new_stream_writable_options">#</a></span></h4>
<div class="signature"><ul>
<li><code>options</code> <span class="type">Object</span><ul>
<li><code>highWaterMark</code> <span class="type">Number</span> Buffer level when <a href="#stream_writable_write_chunk_encoding_callback"><code>write()</code></a> starts
returning false. Default=16kb</li>
<li><code>decodeStrings</code> <span class="type">Boolean</span> Whether or not to decode strings into
Buffers before passing them to <a href="#stream_writable_write_chunk_encoding_callback_1"><code>_write()</code></a>. Default=true</li>
<li><code>objectMode</code> <span class="type">Boolean</span> Whether or not the <code>write(anyObj)</code> is
a valid operation. If set you can write arbitrary data instead
of only <code>Buffer</code> / <code>String</code> data. Default=false</li>
</ul>
</li>
</div></ul>
<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="#all_writable_write_chunk_encoding_callback_1" id="all_writable_write_chunk_encoding_callback_1">#</a></span></h4>
<div class="signature"><ul>
<li><code>chunk</code> <span class="type">Buffer | String</span> The chunk to be written. Will always
be a buffer unless the <code>decodeStrings</code> option was set to <code>false</code>.</li>
<li><code>encoding</code> <span class="type">String</span> If the chunk is a string, then this is the
encoding type. Ignore chunk is a buffer. Note that chunk will
<strong>always</strong> be a buffer unless the <code>decodeStrings</code> option is
explicitly set to <code>false</code>.</li>
<li><code>callback</code> <span class="type">Function</span> Call this function (optionally with an error
argument) when you are done processing the supplied chunk.</li>
</div></ul>
<p>All Writable stream implementations must provide a <a href="#stream_writable_write_chunk_encoding_callback_1"><code>_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>
<h3>Class: stream.Duplex<span><a class="mark" href="#all_class_stream_duplex_1" id="all_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 <code>_read(size)</code> and
<a href="#stream_writable_write_chunk_encoding_callback_1"><code>_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 lowlevel
<code>_read(n)</code> method as well as the lowlevel
<a href="#stream_writable_write_chunk_encoding_callback_1"><code>_write(chunk, encoding, callback)</code></a> method on extension duplex classes.
</p>
<h4>new stream.Duplex(options)<span><a class="mark" href="#all_new_stream_duplex_options" id="all_new_stream_duplex_options">#</a></span></h4>
<div class="signature"><ul>
<li><code>options</code> <span class="type">Object</span> Passed to both Writable and Readable
constructors. Also has the following fields:<ul>
<li><code>allowHalfOpen</code> <span class="type">Boolean</span> Default=true. If set to <code>false</code>, then
the stream will automatically end the readable side when the
writable side ends and vice versa.</li>
</ul>
</li>
</div></ul>
<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.Transform<span><a class="mark" href="#all_class_stream_transform_1" id="all_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>_read()</code></a> and <a href="#stream_writable_write_chunk_encoding_callback_1"><code>_write()</code></a> methods, Transform
classes must implement the <code>_transform()</code> method, and may optionally
also implement the <code>_flush()</code> method. (See below.)
</p>
<h4>new stream.Transform([options])<span><a class="mark" href="#all_new_stream_transform_options" id="all_new_stream_transform_options">#</a></span></h4>
<div class="signature"><ul>
<li><code>options</code> <span class="type">Object</span> Passed to both Writable and Readable
constructors.</li>
</div></ul>
<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>transform._transform(chunk, encoding, callback)<span><a class="mark" href="#all_transform_transform_chunk_encoding_callback" id="all_transform_transform_chunk_encoding_callback">#</a></span></h4>
<div class="signature"><ul>
<li><code>chunk</code> <span class="type">Buffer | String</span> The chunk to be transformed. Will always
be a buffer unless the <code>decodeStrings</code> option was set to <code>false</code>.</li>
<li><code>encoding</code> <span class="type">String</span> If the chunk is a string, then this is the
encoding type. (Ignore if <code>decodeStrings</code> chunk is a buffer.)</li>
<li><code>callback</code> <span class="type">Function</span> Call this function (optionally with an error
argument) when you are done processing the supplied chunk.</li>
</div></ul>
<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.
</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._flush(callback)<span><a class="mark" href="#all_transform_flush_callback" id="all_transform_flush_callback">#</a></span></h4>
<div class="signature"><ul>
<li><code>callback</code> <span class="type">Function</span> Call this function (optionally with an error
argument) when you are done flushing any remaining data.</li>
</div></ul>
<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 <code>end</code> to signal the end of the readable side. Just
like with <code>_transform</code>, 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>Events: 'finish' and 'end'<span><a class="mark" href="#all_events_finish_and_end" id="all_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
<code>.end()</code> is called and all chunks have been processed by <code>_transform</code>,
<code>end</code> is fired after all data has been output which is after the callback
in <code>_flush</code> has been called.
</p>
<h4>Example: <code>SimpleProtocol</code> parser v2<span><a class="mark" href="#all_example_simpleprotocol_parser_v2" id="all_example_simpleprotocol_parser_v2">#</a></span></h4>
<p>The example above 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 above.
</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 stream
approach.
</p>
<pre><code class="javascript">var util = require('util');
var 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.PassThrough<span><a class="mark" href="#all_class_stream_passthrough" id="all_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>
<h2>Streams: Under the Hood<span><a class="mark" href="#all_streams_under_the_hood" id="all_streams_under_the_hood">#</a></span></h2>
<!--type=misc-->
<h3>Buffering<span><a class="mark" href="#all_buffering" id="all_buffering">#</a></span></h3>
<!--type=misc-->
<p>Both Writable and Readable streams will buffer data on an internal
object called <code>_writableState.buffer</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
<code>stream.read()</code>, 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 <code>write()</code> returns <code>false</code>.
</p>
<p>The purpose of streams, especially with the <code>pipe()</code> 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><code>stream.read(0)</code><span><a class="mark" href="#all_stream_read_0" id="all_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>read(0)</code> will trigger
a low-level <code>_read</code> call.
</p>
<p>There is almost never a need to do this. However, you will see some
cases in Node's internals where this is done, particularly in the
Readable stream class internals.
</p>
<h3><code>stream.push('')</code><span><a class="mark" href="#all_stream_push" id="all_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 <code>stream.read(0)</code>. 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">tls.CryptoStream</a> class, which is deprecated in Node v0.12. 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>
<h3>Compatibility with Older Node Versions<span><a class="mark" href="#all_compatibility_with_older_node_versions" id="all_compatibility_with_older_node_versions">#</a></span></h3>
<!--type=misc-->
<p>In versions of Node 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 <code>read()</code> method, <code>'data'</code>
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 <code>pause()</code> method was advisory, rather than guaranteed. This
meant that you still had to be prepared to receive <code>'data'</code> events
even when the stream was in a paused state.</li>
</ul>
<p>In Node v0.10, the Readable class described below was added. For
backwards compatibility with older Node programs, Readable streams
switch into "flowing mode" when a <code>'data'</code> event handler is added, or
when the <code>pause()</code> or <code>resume()</code> methods are called. The effect is
that, even if you are not using the new <code>read()</code> method and
<code>'readable'</code> event, you no longer have to worry about losing <code>'data'</code>
chunks.
</p>
<p>Most programs will continue to function normally. However, this
introduces an edge case in the following conditions:
</p>
<ul>
<li>No <code>'data'</code> event handler is added.</li>
<li>The <code>pause()</code> and <code>resume()</code> methods are never called.</li>
</ul>
<p>For example, consider the following code:
</p>
<pre><code class="javascript">// WARNING! BROKEN!
net.createServer(function(socket) {
// we add an 'end' method, but never consume the data
socket.on('end', function() {
// 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 prior to v0.10, the incoming message data would be
simply discarded. However, in Node v0.10 and beyond, the socket will
remain paused forever.
</p>
<p>The workaround in this situation is to call the <code>resume()</code> method to
trigger "old mode" behavior:
</p>
<pre><code class="javascript">// Workaround
net.createServer(function(socket) {
socket.on('end', function() {
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 <code>wrap()</code>
method.
</p>
<h3>Object Mode<span><a class="mark" href="#all_object_mode" id="all_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 <code>stream.read(size)</code>, regardless of what the size argument
is.
</p>
<p>A Writable stream in object mode will always ignore the <code>encoding</code>
argument to <code>stream.write(data, encoding)</code>.
</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 <code>stream.read()</code> 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 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>
<h3>State Objects<span><a class="mark" href="#all_state_objects" id="all_state_objects">#</a></span></h3>
<p><a href="#stream_class_stream_readable">Readable</a> streams have a member object called <code>_readableState</code>.
<a href="#stream_class_stream_writable">Writable</a> streams have a member object called <code>_writableState</code>.
<a href="#stream_class_stream_duplex">Duplex</a> streams have both.
</p>
<p><strong>These objects should generally not be modified in child classes.</strong>
However, if you have a Duplex or Transform stream that should be in
<code>objectMode</code> on the readable side, and not in <code>objectMode</code> on the
writable side, then you may do this in the constructor by setting the
flag explicitly on the appropriate state object.
</p>
<pre><code class="javascript">var util = require('util');
var StringDecoder = require('string_decoder').StringDecoder;
var Transform = require('stream').Transform;
util.inherits(JSONParseStream, Transform);
// Gets \n-delimited JSON string data, and emits the parsed objects
function JSONParseStream(options) {
if (!(this instanceof JSONParseStream))
return new JSONParseStream(options);
Transform.call(this, options);
this._writableState.objectMode = false;
this._readableState.objectMode = 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>
<p>The state objects contain other useful information for debugging the
state of streams in your programs. It is safe to look at them, but
beyond setting option flags in the constructor, it is <strong>not</strong> safe to
modify them.
</p>
<h1>Crypto<span><a class="mark" href="#all_crypto" id="all_crypto">#</a></span></h1>
<pre class="api_stability_2">Stability: 2 - Unstable; API changes are being discussed for
future versions. Breaking changes will be minimized. See below.</pre><p>Use <code>require('crypto')</code> to access this module.
</p>
<p>The crypto module offers a way of encapsulating secure credentials to be
used as part of a secure HTTPS net or http connection.
</p>
<p>It also offers a set of wrappers for OpenSSL's hash, hmac, cipher,
decipher, sign and verify methods.
</p>
<h2>crypto.getCiphers()<span><a class="mark" href="#all_crypto_getciphers" id="all_crypto_getciphers">#</a></span></h2>
<p>Returns an array with the names of the supported ciphers.
</p>
<p>Example:
</p>
<pre><code>var ciphers = crypto.getCiphers();
console.log(ciphers); // ['AES-128-CBC', 'AES-128-CBC-HMAC-SHA1', ...]</code></pre>
<h2>crypto.getHashes()<span><a class="mark" href="#all_crypto_gethashes" id="all_crypto_gethashes">#</a></span></h2>
<p>Returns an array with the names of the supported hash algorithms.
</p>
<p>Example:
</p>
<pre><code>var hashes = crypto.getHashes();
console.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...]</code></pre>
<h2>crypto.createCredentials(details)<span><a class="mark" href="#all_crypto_createcredentials_details" id="all_crypto_createcredentials_details">#</a></span></h2>
<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 holding the PEM encoded private key</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> : Either a string or list of strings of PEM encoded CA
certificates to trust.</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="http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT">http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT</a>
for details on the format.</li>
</ul>
<p>If no 'ca' details are given, then node.js will use the default
publicly trusted list of CAs as given in
</p>
<p><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>crypto.createHash(algorithm)<span><a class="mark" href="#all_crypto_createhash_algorithm" id="all_crypto_createhash_algorithm">#</a></span></h2>
<p>Creates and returns a hash object, a cryptographic hash with the given
algorithm which can be used to generate hash digests.
</p>
<p><code>algorithm</code> is dependent on the available algorithms supported by the
version of OpenSSL on the platform. Examples are <code>'sha1'</code>, <code>'md5'</code>,
<code>'sha256'</code>, <code>'sha512'</code>, etc. On recent releases, <code>openssl
list-message-digest-algorithms</code> will display the available digest
algorithms.
</p>
<p>Example: this program that takes the sha1 sum of a file
</p>
<pre><code>var filename = process.argv[2];
var crypto = require('crypto');
var fs = require('fs');
var shasum = crypto.createHash('sha1');
var s = fs.ReadStream(filename);
s.on('data', function(d) {
shasum.update(d);
});
s.on('end', function() {
var d = shasum.digest('hex');
console.log(d + ' ' + filename);
});</code></pre>
<h2>Class: Hash<span><a class="mark" href="#all_class_hash" id="all_class_hash">#</a></span></h2>
<p>The class for creating hash digests of data.
</p>
<p>It is a <a href="stream.html">stream</a> that is both readable and writable. The
written data is used to compute the hash. Once the writable side of
the stream is ended, use the <code>read()</code> method to get the computed hash
digest. The legacy <code>update</code> and <code>digest</code> methods are also supported.
</p>
<p>Returned by <code>crypto.createHash</code>.
</p>
<h3>hash.update(data, [input_encoding])<span><a class="mark" href="#all_hash_update_data_input_encoding" id="all_hash_update_data_input_encoding">#</a></span></h3>
<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 no encoding is provided and the input is a string an
encoding of <code>'binary'</code> is enforced. If <code>data</code> is a <code>Buffer</code> then
<code>input_encoding</code> is ignored.
</p>
<p>This can be called many times with new data as it is streamed.
</p>
<h3>hash.digest([encoding])<span><a class="mark" href="#all_hash_digest_encoding" id="all_hash_digest_encoding">#</a></span></h3>
<p>Calculates the digest of all of the passed data to be hashed. The
<code>encoding</code> can be <code>'hex'</code>, <code>'binary'</code> or <code>'base64'</code>. If no encoding
is provided, then a buffer is returned.
</p>
<p>Note: <code>hash</code> object can not be used after <code>digest()</code> method has been
called.
</p>
<h2>crypto.createHmac(algorithm, key)<span><a class="mark" href="#all_crypto_createhmac_algorithm_key" id="all_crypto_createhmac_algorithm_key">#</a></span></h2>
<p>Creates and returns a hmac object, a cryptographic hmac with the given
algorithm and key.
</p>
<p>It is a <a href="stream.html">stream</a> that is both readable and writable. The
written data is used to compute the hmac. Once the writable side of
the stream is ended, use the <code>read()</code> method to get the computed
digest. The legacy <code>update</code> and <code>digest</code> methods are also supported.
</p>
<p><code>algorithm</code> is dependent on the available algorithms supported by
OpenSSL - see createHash above. <code>key</code> is the hmac key to be used.
</p>
<h2>Class: Hmac<span><a class="mark" href="#all_class_hmac" id="all_class_hmac">#</a></span></h2>
<p>Class for creating cryptographic hmac content.
</p>
<p>Returned by <code>crypto.createHmac</code>.
</p>
<h3>hmac.update(data)<span><a class="mark" href="#all_hmac_update_data" id="all_hmac_update_data">#</a></span></h3>
<p>Update the hmac content with the given <code>data</code>. This can be called
many times with new data as it is streamed.
</p>
<h3>hmac.digest([encoding])<span><a class="mark" href="#all_hmac_digest_encoding" id="all_hmac_digest_encoding">#</a></span></h3>
<p>Calculates the digest of all of the passed data to the hmac. The
<code>encoding</code> can be <code>'hex'</code>, <code>'binary'</code> or <code>'base64'</code>. If no encoding
is provided, then a buffer is returned.
</p>
<p>Note: <code>hmac</code> object can not be used after <code>digest()</code> method has been
called.
</p>
<h2>crypto.createCipher(algorithm, password)<span><a class="mark" href="#all_crypto_createcipher_algorithm_password" id="all_crypto_createcipher_algorithm_password">#</a></span></h2>
<p>Creates and returns a cipher object, with the given algorithm and
password.
</p>
<p><code>algorithm</code> is dependent on OpenSSL, examples are <code>'aes192'</code>, etc. On
recent releases, <code>openssl list-cipher-algorithms</code> will display the
available cipher algorithms. <code>password</code> is used to derive key and IV,
which must be a <code>'binary'</code> encoded string or a <a href="buffer.html">buffer</a>.
</p>
<p>It is a <a href="stream.html">stream</a> that is both readable and writable. The
written data is used to compute the hash. Once the writable side of
the stream is ended, use the <code>read()</code> method to get the computed hash
digest. The legacy <code>update</code> and <code>digest</code> methods are also supported.
</p>
<h2>crypto.createCipheriv(algorithm, key, iv)<span><a class="mark" href="#all_crypto_createcipheriv_algorithm_key_iv" id="all_crypto_createcipheriv_algorithm_key_iv">#</a></span></h2>
<p>Creates and returns a cipher object, with the given algorithm, key and
iv.
</p>
<p><code>algorithm</code> is the same as the argument to <code>createCipher()</code>. <code>key</code> is
the raw key used by the algorithm. <code>iv</code> is an <a href="http://en.wikipedia.org/wiki/Initialization_vector">initialization
vector</a>.
</p>
<p><code>key</code> and <code>iv</code> must be <code>'binary'</code> encoded strings or
<a href="buffer.html">buffers</a>.
</p>
<h2>Class: Cipher<span><a class="mark" href="#all_class_cipher" id="all_class_cipher">#</a></span></h2>
<p>Class for encrypting data.
</p>
<p>Returned by <code>crypto.createCipher</code> and <code>crypto.createCipheriv</code>.
</p>
<p>Cipher objects are <a href="stream.html">streams</a> that are both readable and
writable. The written plain text data is used to produce the
encrypted data on the readable side. The legacy <code>update</code> and <code>final</code>
methods are also supported.
</p>
<h3>cipher.update(data, [input_encoding], [output_encoding])<span><a class="mark" href="#all_cipher_update_data_input_encoding_output_encoding" id="all_cipher_update_data_input_encoding_output_encoding">#</a></span></h3>
<p>Updates the cipher with <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 no
encoding is provided, then a buffer is expected.
If <code>data</code> is a <code>Buffer</code> 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 no encoding is
provided, then a buffer is returned.
</p>
<p>Returns the enciphered contents, and can be called many times with new
data as it is streamed.
</p>
<h3>cipher.final([output_encoding])<span><a class="mark" href="#all_cipher_final_output_encoding" id="all_cipher_final_output_encoding">#</a></span></h3>
<p>Returns any remaining enciphered contents, with <code>output_encoding</code>
being one of: <code>'binary'</code>, <code>'base64'</code> or <code>'hex'</code>. If no encoding is
provided, then a buffer is returned.
</p>
<p>Note: <code>cipher</code> object can not be used after <code>final()</code> method has been
called.
</p>
<h3>cipher.setAutoPadding(auto_padding=true)<span><a class="mark" href="#all_cipher_setautopadding_auto_padding_true" id="all_cipher_setautopadding_auto_padding_true">#</a></span></h3>
<p>You can disable automatic padding of the input data to block size. If
<code>auto_padding</code> is false, the length of the entire input data must be a
multiple of the cipher's block size or <code>final</code> will fail. Useful for
non-standard padding, e.g. using <code>0x0</code> instead of PKCS padding. You
must call this before <code>cipher.final</code>.
</p>
<h2>crypto.createDecipher(algorithm, password)<span><a class="mark" href="#all_crypto_createdecipher_algorithm_password" id="all_crypto_createdecipher_algorithm_password">#</a></span></h2>
<p>Creates and returns a decipher object, with the given algorithm and
key. This is the mirror of the <a href="#crypto_crypto_createcipher_algorithm_password">createCipher()</a> above.
</p>
<h2>crypto.createDecipheriv(algorithm, key, iv)<span><a class="mark" href="#all_crypto_createdecipheriv_algorithm_key_iv" id="all_crypto_createdecipheriv_algorithm_key_iv">#</a></span></h2>
<p>Creates and returns a decipher object, with the given algorithm, key
and iv. This is the mirror of the <a href="#crypto_crypto_createcipheriv_algorithm_key_iv">createCipheriv()</a> above.
</p>
<h2>Class: Decipher<span><a class="mark" href="#all_class_decipher" id="all_class_decipher">#</a></span></h2>
<p>Class for decrypting data.
</p>
<p>Returned by <code>crypto.createDecipher</code> and <code>crypto.createDecipheriv</code>.
</p>
<p>Decipher objects are <a href="stream.html">streams</a> that are both readable and
writable. The written enciphered data is used to produce the
plain-text data on the the readable side. The legacy <code>update</code> and
<code>final</code> methods are also supported.
</p>
<h3>decipher.update(data, [input_encoding], [output_encoding])<span><a class="mark" href="#all_decipher_update_data_input_encoding_output_encoding" id="all_decipher_update_data_input_encoding_output_encoding">#</a></span></h3>
<p>Updates the decipher with <code>data</code>, which is encoded in <code>'binary'</code>,
<code>'base64'</code> or <code>'hex'</code>. If no encoding is provided, then a buffer is
expected.
If <code>data</code> is a <code>Buffer</code> then <code>input_encoding</code> is ignored.
</p>
<p>The <code>output_decoding</code> specifies in what format to return the
deciphered plaintext: <code>'binary'</code>, <code>'ascii'</code> or <code>'utf8'</code>. If no
encoding is provided, then a buffer is returned.
</p>
<h3>decipher.final([output_encoding])<span><a class="mark" href="#all_decipher_final_output_encoding" id="all_decipher_final_output_encoding">#</a></span></h3>
<p>Returns any remaining plaintext which is deciphered, with
<code>output_encoding</code> being one of: <code>'binary'</code>, <code>'ascii'</code> or <code>'utf8'</code>. If
no encoding is provided, then a buffer is returned.
</p>
<p>Note: <code>decipher</code> object can not be used after <code>final()</code> method has been
called.
</p>
<h3>decipher.setAutoPadding(auto_padding=true)<span><a class="mark" href="#all_decipher_setautopadding_auto_padding_true" id="all_decipher_setautopadding_auto_padding_true">#</a></span></h3>
<p>You can disable auto padding if the data has been encrypted without
standard block padding to prevent <code>decipher.final</code> from checking and
removing it. Can only work if the input data's length is a multiple of
the ciphers block size. You must call this before streaming data to
<code>decipher.update</code>.
</p>
<h2>crypto.createSign(algorithm)<span><a class="mark" href="#all_crypto_createsign_algorithm" id="all_crypto_createsign_algorithm">#</a></span></h2>
<p>Creates and returns a signing object, with the given algorithm. On
recent OpenSSL releases, <code>openssl list-public-key-algorithms</code> will
display the available signing algorithms. Examples are <code>'RSA-SHA256'</code>.
</p>
<h2>Class: Sign<span><a class="mark" href="#all_class_sign" id="all_class_sign">#</a></span></h2>
<p>Class for generating signatures.
</p>
<p>Returned by <code>crypto.createSign</code>.
</p>
<p>Sign objects are writable <a href="stream.html">streams</a>. The written data is
used to generate the signature. Once all of the data has been
written, the <code>sign</code> method will return the signature. The legacy
<code>update</code> method is also supported.
</p>
<h3>sign.update(data)<span><a class="mark" href="#all_sign_update_data" id="all_sign_update_data">#</a></span></h3>
<p>Updates the sign object with data. This can be called many times
with new data as it is streamed.
</p>
<h3>sign.sign(private_key, [output_format])<span><a class="mark" href="#all_sign_sign_private_key_output_format" id="all_sign_sign_private_key_output_format">#</a></span></h3>
<p>Calculates the signature on all the updated data passed through the
sign. <code>private_key</code> is a string containing the PEM encoded private
key for signing.
</p>
<p>Returns the signature in <code>output_format</code> which can be <code>'binary'</code>,
<code>'hex'</code> or <code>'base64'</code>. If no encoding is provided, then a buffer is
returned.
</p>
<p>Note: <code>sign</code> object can not be used after <code>sign()</code> method has been
called.
</p>
<h2>crypto.createVerify(algorithm)<span><a class="mark" href="#all_crypto_createverify_algorithm" id="all_crypto_createverify_algorithm">#</a></span></h2>
<p>Creates and returns a verification object, with the given algorithm.
This is the mirror of the signing object above.
</p>
<h2>Class: Verify<span><a class="mark" href="#all_class_verify" id="all_class_verify">#</a></span></h2>
<p>Class for verifying signatures.
</p>
<p>Returned by <code>crypto.createVerify</code>.
</p>
<p>Verify objects are writable <a href="stream.html">streams</a>. The written data
is used to validate against the supplied signature. Once all of the
data has been written, the <code>verify</code> method will return true if the
supplied signature is valid. The legacy <code>update</code> method is also
supported.
</p>
<h3>verifier.update(data)<span><a class="mark" href="#all_verifier_update_data" id="all_verifier_update_data">#</a></span></h3>
<p>Updates the verifier object with data. 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="#all_verifier_verify_object_signature_signature_format" id="all_verifier_verify_object_signature_signature_format">#</a></span></h3>
<p>Verifies the signed data by using the <code>object</code> and <code>signature</code>.
<code>object</code> is a string containing a PEM encoded object, which can be
one of RSA public key, DSA public key, or X.509 certificate.
<code>signature</code> 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 no encoding is specified, then a buffer is expected.
</p>
<p>Returns true or false depending on the validity of the signature for
the data and public key.
</p>
<p>Note: <code>verifier</code> object can not be used after <code>verify()</code> method has been
called.
</p>
<h2>crypto.createDiffieHellman(prime_length)<span><a class="mark" href="#all_crypto_creatediffiehellman_prime_length" id="all_crypto_creatediffiehellman_prime_length">#</a></span></h2>
<p>Creates a Diffie-Hellman key exchange object and generates a prime of
the given bit length. The generator used is <code>2</code>.
</p>
<h2>crypto.createDiffieHellman(prime, [encoding])<span><a class="mark" href="#all_crypto_creatediffiehellman_prime_encoding" id="all_crypto_creatediffiehellman_prime_encoding">#</a></span></h2>
<p>Creates a Diffie-Hellman key exchange object using the supplied prime.
The generator used is <code>2</code>. Encoding can be <code>'binary'</code>, <code>'hex'</code>, or
<code>'base64'</code>. If no encoding is specified, then a buffer is expected.
</p>
<h2>Class: DiffieHellman<span><a class="mark" href="#all_class_diffiehellman" id="all_class_diffiehellman">#</a></span></h2>
<p>The class for creating Diffie-Hellman key exchanges.
</p>
<p>Returned by <code>crypto.createDiffieHellman</code>.
</p>
<h3>diffieHellman.generateKeys([encoding])<span><a class="mark" href="#all_diffiehellman_generatekeys_encoding" id="all_diffiehellman_generatekeys_encoding">#</a></span></h3>
<p>Generates private and public Diffie-Hellman key values, and returns
the public key in the specified encoding. This key should be
transferred to the other party. Encoding can be <code>'binary'</code>, <code>'hex'</code>,
or <code>'base64'</code>. If no encoding is provided, then a buffer is returned.
</p>
<h3>diffieHellman.computeSecret(other_public_key, [input_encoding], [output_encoding])<span><a class="mark" href="#all_diffiehellman_computesecret_other_public_key_input_encoding_output_encoding" id="all_diffiehellman_computesecret_other_public_key_input_encoding_output_encoding">#</a></span></h3>
<p>Computes the shared secret using <code>other_public_key</code> as the other
party's public key and returns the computed shared secret. Supplied
key is interpreted using 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 input encoding is not
provided, then a buffer is expected.
</p>
<p>If no output encoding is given, then a buffer is returned.
</p>
<h3>diffieHellman.getPrime([encoding])<span><a class="mark" href="#all_diffiehellman_getprime_encoding" id="all_diffiehellman_getprime_encoding">#</a></span></h3>
<p>Returns the Diffie-Hellman prime in the specified encoding, which can
be <code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>. If no encoding is provided,
then a buffer is returned.
</p>
<h3>diffieHellman.getGenerator([encoding])<span><a class="mark" href="#all_diffiehellman_getgenerator_encoding" id="all_diffiehellman_getgenerator_encoding">#</a></span></h3>
<p>Returns the Diffie-Hellman generator in the specified encoding, which can
be <code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>. If no encoding is provided,
then a buffer is returned.
</p>
<h3>diffieHellman.getPublicKey([encoding])<span><a class="mark" href="#all_diffiehellman_getpublickey_encoding" id="all_diffiehellman_getpublickey_encoding">#</a></span></h3>
<p>Returns the Diffie-Hellman public key in the specified encoding, which
can be <code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>. If no encoding is provided,
then a buffer is returned.
</p>
<h3>diffieHellman.getPrivateKey([encoding])<span><a class="mark" href="#all_diffiehellman_getprivatekey_encoding" id="all_diffiehellman_getprivatekey_encoding">#</a></span></h3>
<p>Returns the Diffie-Hellman private key in the specified encoding,
which can be <code>'binary'</code>, <code>'hex'</code>, or <code>'base64'</code>. If no encoding is
provided, then a buffer is returned.
</p>
<h3>diffieHellman.setPublicKey(public_key, [encoding])<span><a class="mark" href="#all_diffiehellman_setpublickey_public_key_encoding" id="all_diffiehellman_setpublickey_public_key_encoding">#</a></span></h3>
<p>Sets the Diffie-Hellman public key. Key encoding can be <code>'binary'</code>,
<code>'hex'</code> or <code>'base64'</code>. If no encoding is provided, then a buffer is
expected.
</p>
<h3>diffieHellman.setPrivateKey(private_key, [encoding])<span><a class="mark" href="#all_diffiehellman_setprivatekey_private_key_encoding" id="all_diffiehellman_setprivatekey_private_key_encoding">#</a></span></h3>
<p>Sets the Diffie-Hellman private key. Key encoding can be <code>'binary'</code>,
<code>'hex'</code> or <code>'base64'</code>. If no encoding is provided, then a buffer is
expected.
</p>
<h2>crypto.getDiffieHellman(group_name)<span><a class="mark" href="#all_crypto_getdiffiehellman_group_name" id="all_crypto_getdiffiehellman_group_name">#</a></span></h2>
<p>Creates a predefined Diffie-Hellman key exchange object. The
supported groups are: <code>'modp1'</code>, <code>'modp2'</code>, <code>'modp5'</code> (defined in <a href="http://www.rfc-editor.org/rfc/rfc2412.txt">RFC
2412</a>) and <code>'modp14'</code>, <code>'modp15'</code>, <code>'modp16'</code>, <code>'modp17'</code>,
<code>'modp18'</code> (defined in <a href="http://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_encoding">crypto.createDiffieHellman()</a>
above, but will not allow to change the keys (with
<a href="#crypto_diffiehellman_setpublickey_public_key_encoding">diffieHellman.setPublicKey()</a> for example). The advantage of using
this routine is that the parties don't have to generate nor exchange
group modulus beforehand, saving both processor and communication
time.
</p>
<p>Example (obtaining a shared secret):
</p>
<pre><code>var crypto = require('crypto');
var alice = crypto.getDiffieHellman('modp5');
var bob = crypto.getDiffieHellman('modp5');
alice.generateKeys();
bob.generateKeys();
var alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
var 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>
<h2>crypto.pbkdf2(password, salt, iterations, keylen, callback)<span><a class="mark" href="#all_crypto_pbkdf2_password_salt_iterations_keylen_callback" id="all_crypto_pbkdf2_password_salt_iterations_keylen_callback">#</a></span></h2>
<p>Asynchronous PBKDF2 applies pseudorandom function HMAC-SHA1 to derive
a key of given length from the given password, salt and iterations.
The callback gets two arguments <code>(err, derivedKey)</code>.
</p>
<h2>crypto.pbkdf2Sync(password, salt, iterations, keylen)<span><a class="mark" href="#all_crypto_pbkdf2sync_password_salt_iterations_keylen" id="all_crypto_pbkdf2sync_password_salt_iterations_keylen">#</a></span></h2>
<p>Synchronous PBKDF2 function. Returns derivedKey or throws error.
</p>
<h2>crypto.randomBytes(size, [callback])<span><a class="mark" href="#all_crypto_randombytes_size_callback" id="all_crypto_randombytes_size_callback">#</a></span></h2>
<p>Generates cryptographically strong pseudo-random data. Usage:
</p>
<pre><code>// async
crypto.randomBytes(256, function(ex, buf) {
if (ex) throw ex;
console.log('Have %d bytes of random data: %s', buf.length, buf);
});
// sync
try {
var buf = crypto.randomBytes(256);
console.log('Have %d bytes of random data: %s', buf.length, buf);
} catch (ex) {
// handle error
// most likely, entropy sources are drained
}</code></pre>
<p>NOTE: Will throw error or invoke callback with error, if there is not enough
accumulated entropy to generate cryptographically strong data. In other words,
<code>crypto.randomBytes</code> without callback will not block even if all entropy sources
are drained.
</p>
<h2>crypto.pseudoRandomBytes(size, [callback])<span><a class="mark" href="#all_crypto_pseudorandombytes_size_callback" id="all_crypto_pseudorandombytes_size_callback">#</a></span></h2>
<p>Generates <em>non</em>-cryptographically strong pseudo-random data. The data
returned will be unique if it is sufficiently long, but is not
necessarily unpredictable. For this reason, the output of this
function should never be used where unpredictability is important,
such as in the generation of encryption keys.
</p>
<p>Usage is otherwise identical to <code>crypto.randomBytes</code>.
</p>
<h2>crypto.DEFAULT_ENCODING<span><a class="mark" href="#all_crypto_default_encoding" id="all_crypto_default_encoding">#</a></span></h2>
<p>The default encoding to use for functions that can take either strings
or buffers. The default value is <code>'buffer'</code>, which makes it default
to using Buffer objects. This is here to make the crypto module more
easily compatible with legacy programs that expected <code>'binary'</code> to be
the default encoding.
</p>
<p>Note that new programs will probably expect buffers, so only use this
as a temporary measure.
</p>
<h2>Recent API Changes<span><a class="mark" href="#all_recent_api_changes" id="all_recent_api_changes">#</a></span></h2>
<p>The Crypto module was added to Node before there was the concept of a
unified Stream API, and before there were Buffer objects for handling
binary data.
</p>
<p>As such, the streaming classes don't have the typical methods found on
other Node classes, and many methods accepted and returned
Binary-encoded strings by default rather than Buffers. This was
changed to use Buffers by default instead.
</p>
<p>This is a breaking change for some use cases, but not all.
</p>
<p>For example, if you currently use the default arguments to the Sign
class, and then pass the results to the Verify class, without ever
inspecting the data, then it will continue to work as before. Where
you once got a binary string and then presented the binary string to
the Verify object, you'll now get a Buffer, and present the Buffer to
the Verify object.
</p>
<p>However, if you were doing things with the string data that will not
work properly on Buffers (such as, concatenating them, storing in
databases, etc.), or you are passing binary strings to the crypto
functions without an encoding argument, then you will need to start
providing encoding arguments to specify which encoding you'd like to
use. To switch to the previous style of using binary strings by
default, set the <code>crypto.DEFAULT_ENCODING</code> field to 'binary'. Note
that new programs will probably expect buffers, so only use this as a
temporary measure.
</p>
<h1>TLS (SSL)<span><a class="mark" href="#all_tls_ssl" id="all_tls_ssl">#</a></span></h1>
<pre class="api_stability_3">Stability: 3 - 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 1024</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 -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>(TODO: docs on creating a CA, for now interested users should just look at
<code>test/fixtures/keys/Makefile</code> in the Node source code)
</p>
<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="#all_client_initiated_renegotiation_attack_mitigation" id="all_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_cleartextstream">CleartextStream</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>NPN and SNI<span><a class="mark" href="#all_npn_and_sni" id="all_npn_and_sni">#</a></span></h2>
<!-- type=misc -->
<p>NPN (Next Protocol Negotiation) and SNI (Server Name Indication) are TLS
handshake extensions allowing you:
</p>
<ul>
<li>NPN - to use one TLS server for multiple protocols (HTTP, SPDY)</li>
<li>SNI - to use one TLS server for multiple hostnames with different SSL
certificates.</li>
</ul>
<h2>tls.getCiphers()<span><a class="mark" href="#all_tls_getciphers" id="all_tls_getciphers">#</a></span></h2>
<p>Returns an array with the names of the supported SSL ciphers.
</p>
<p>Example:
</p>
<pre><code>var ciphers = tls.getCiphers();
console.log(ciphers); // ['AES128-SHA', 'AES256-SHA', ...]</code></pre>
<h2>tls.createServer(options, [secureConnectionListener])<span><a class="mark" href="#all_tls_createserver_options_secureconnectionlistener" id="all_tls_createserver_options_secureconnectionlistener">#</a></span></h2>
<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">secureConnection</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. (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. (Required)</p>
</li>
<li><p><code>ca</code>: An 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.</p>
<p>To mitigate <a href="http://blog.ivanristic.com/2011/10/mitigating-the-beast-attack-on-tls.html">BEAST attacks</a> it is recommended that you use this option in
conjunction with the <code>honorCipherOrder</code> option described below to
prioritize the non-CBC cipher.</p>
<p>Defaults to <code>AES128-GCM-SHA256:RC4:HIGH:!MD5:!aNULL:!EDH</code>.
Consult the <a href="http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT">OpenSSL cipher list format documentation</a> for details on the
format. ECDH (Elliptic Curve Diffie-Hellman) ciphers are not yet supported.</p>
</li>
</ul>
<pre><code>`AES128-GCM-SHA256` is used when node.js is linked against OpenSSL 1.0.1
or newer and the client speaks TLS 1.2, RC4 is used as a secure fallback.
**NOTE**: Previous revisions of this section suggested `AES256-SHA` as an
acceptable cipher. Unfortunately, `AES256-SHA` is a CBC cipher and therefore
susceptible to BEAST attacks. Do *not* use it.</code></pre>
<ul>
<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.</p>
<p>Note that if SSLv2 is used, the server will send its list of preferences
to the client, and the client chooses the cipher.</p>
<p>Although, this option is disabled by default, it is <em>recommended</em> that you
use this option in conjunction with the <code>ciphers</code> option to mitigate
BEAST attacks.</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>SNICallback</code>: A function that will be called if client supports SNI TLS
extension. Only one argument will be passed to it: <code>servername</code>. And
<code>SNICallback</code> should return SecureContext instance.
(You can use <code>crypto.createCredentials(...).context</code> to get proper
SecureContext). If <code>SNICallback</code> wasn't provided - default callback with
high-level API will be used (see below).</p>
</li>
<li><p><code>sessionIdContext</code>: A string containing a opaque identifier for session
resumption. If <code>requestCert</code> is <code>true</code>, the default is MD5 hash value
generated from command-line. 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="http://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>var tls = require('tls');
var fs = require('fs');
var 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, function(cleartextStream) {
console.log('server connected',
cleartextStream.authorized ? 'authorized' : 'unauthorized');
cleartextStream.write("welcome!\n");
cleartextStream.setEncoding('utf8');
cleartextStream.pipe(cleartextStream);
});
server.listen(8000, function() {
console.log('server bound');
});</code></pre>
<p>Or
</p>
<pre><code>var tls = require('tls');
var fs = require('fs');
var options = {
pfx: fs.readFileSync('server.pfx'),
// This is necessary only if using the client certificate authentication.
requestCert: true,
};
var server = tls.createServer(options, function(cleartextStream) {
console.log('server connected',
cleartextStream.authorized ? 'authorized' : 'unauthorized');
cleartextStream.write("welcome!\n");
cleartextStream.setEncoding('utf8');
cleartextStream.pipe(cleartextStream);
});
server.listen(8000, function() {
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.SLAB_BUFFER_SIZE<span><a class="mark" href="#all_tls_slab_buffer_size" id="all_tls_slab_buffer_size">#</a></span></h2>
<p>Size of slab buffer used by all tls servers and clients.
Default: <code>10 * 1024 * 1024</code>.
</p>
<p>Don't change the defaults unless you know what you are doing.
</p>
<h2>tls.connect(options, [callback])<span><a class="mark" href="#all_tls_connect_options_callback" id="all_tls_connect_options_callback">#</a></span></h2>
<h2>tls.connect(port, [host], [options], [callback])<span><a class="mark" href="#all_tls_connect_port_host_options_callback" id="all_tls_connect_port_host_options_callback">#</a></span></h2>
<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>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.</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.</p>
</li>
<li><p><code>ca</code>: An 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>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. 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>servername</code>: Servername for SNI (Server Name Indication) TLS extension.</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="http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_PROTOCOL_METHODS">SSL_METHODS</a>.</p>
</li>
</ul>
<p>The <code>callback</code> parameter will be added as a listener for the
<a href="#tls_event_secureconnect">'secureConnect'</a> event.
</p>
<p><code>tls.connect()</code> returns a <a href="#tls_class_tls_cleartextstream">CleartextStream</a> object.
</p>
<p>Here is an example of a client of echo server as described previously:
</p>
<pre><code>var tls = require('tls');
var fs = require('fs');
var 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 cleartextStream = tls.connect(8000, options, function() {
console.log('client connected',
cleartextStream.authorized ? 'authorized' : 'unauthorized');
process.stdin.pipe(cleartextStream);
process.stdin.resume();
});
cleartextStream.setEncoding('utf8');
cleartextStream.on('data', function(data) {
console.log(data);
});
cleartextStream.on('end', function() {
server.close();
});</code></pre>
<p>Or
</p>
<pre><code>var tls = require('tls');
var fs = require('fs');
var options = {
pfx: fs.readFileSync('client.pfx')
};
var cleartextStream = tls.connect(8000, options, function() {
console.log('client connected',
cleartextStream.authorized ? 'authorized' : 'unauthorized');
process.stdin.pipe(cleartextStream);
process.stdin.resume();
});
cleartextStream.setEncoding('utf8');
cleartextStream.on('data', function(data) {
console.log(data);
});
cleartextStream.on('end', function() {
server.close();
});</code></pre>
<h2>tls.createSecurePair([credentials], [isServer], [requestCert], [rejectUnauthorized])<span><a class="mark" href="#all_tls_createsecurepair_credentials_isserver_requestcert_rejectunauthorized" id="all_tls_createsecurepair_credentials_isserver_requestcert_rejectunauthorized">#</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 credentials object from crypto.createCredentials( ... )</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>
</ul>
<p><code>tls.createSecurePair()</code> returns a SecurePair object with [cleartext][] and
<code>encrypted</code> stream properties.
</p>
<h2>Class: SecurePair<span><a class="mark" href="#all_class_securepair" id="all_class_securepair">#</a></span></h2>
<p>Returned by tls.createSecurePair.
</p>
<h3>Event: 'secure'<span><a class="mark" href="#all_event_secure" id="all_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 'secureConnection' 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="#all_class_tls_server" id="all_class_tls_server">#</a></span></h2>
<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: 'secureConnection'<span><a class="mark" href="#all_event_secureconnection" id="all_event_secureconnection">#</a></span></h3>
<p><code>function (cleartextStream) {}</code>
</p>
<p>This event is emitted after a new connection has been successfully
handshaked. The argument is a instance of <a href="#tls_class_tls_cleartextstream">CleartextStream</a>. It has all the
common stream methods and events.
</p>
<p><code>cleartextStream.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>cleartextStream.authorized</code> is false, then
<code>cleartextStream.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.
<code>cleartextStream.npnProtocol</code> is a string containing selected NPN protocol.
<code>cleartextStream.servername</code> is a string containing servername requested with
SNI.
</p>
<h3>Event: 'clientError'<span><a class="mark" href="#all_event_clienterror" id="all_event_clienterror">#</a></span></h3>
<p><code>function (exception, securePair) { }</code>
</p>
<p>When a client connection emits an 'error' event before secure connection is
established - it will be forwarded here.
</p>
<p><code>securePair</code> is the <code>tls.SecurePair</code> that the error originated from.
</p>
<h3>Event: 'newSession'<span><a class="mark" href="#all_event_newsession" id="all_event_newsession">#</a></span></h3>
<p><code>function (sessionId, sessionData) { }</code>
</p>
<p>Emitted on creation of TLS session. May be used to store sessions in external
storage.
</p>
<h3>Event: 'resumeSession'<span><a class="mark" href="#all_event_resumesession" id="all_event_resumesession">#</a></span></h3>
<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>
<h3>server.listen(port, [host], [callback])<span><a class="mark" href="#all_server_listen_port_host_callback" id="all_server_listen_port_host_callback">#</a></span></h3>
<p>Begin accepting connections on the specified <code>port</code> and <code>host</code>. If the
<code>host</code> is omitted, the server will accept connections directed to any
IPv4 address (<code>INADDR_ANY</code>).
</p>
<p>This function is asynchronous. The last parameter <code>callback</code> will be called
when the server has been bound.
</p>
<p>See <code>net.Server</code> for more information.
</p>
<h3>server.close()<span><a class="mark" href="#all_server_close" id="all_server_close">#</a></span></h3>
<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.
</p>
<h3>server.address()<span><a class="mark" href="#all_server_address" id="all_server_address">#</a></span></h3>
<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">net.Server.address()</a> for
more information.
</p>
<h3>server.addContext(hostname, credentials)<span><a class="mark" href="#all_server_addcontext_hostname_credentials" id="all_server_addcontext_hostname_credentials">#</a></span></h3>
<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>credentials</code> can contain
<code>key</code>, <code>cert</code> and <code>ca</code>.
</p>
<h3>server.maxConnections<span><a class="mark" href="#all_server_maxconnections" id="all_server_maxconnections">#</a></span></h3>
<p>Set this property to reject connections when the server's connection count
gets high.
</p>
<h3>server.connections<span><a class="mark" href="#all_server_connections" id="all_server_connections">#</a></span></h3>
<p>The number of concurrent connections on the server.
</p>
<h2>Class: CryptoStream<span><a class="mark" href="#all_class_cryptostream" id="all_class_cryptostream">#</a></span></h2>
<p>This is an encrypted stream.
</p>
<h3>cryptoStream.bytesWritten<span><a class="mark" href="#all_cryptostream_byteswritten" id="all_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: tls.CleartextStream<span><a class="mark" href="#all_class_tls_cleartextstream" id="all_class_tls_cleartextstream">#</a></span></h2>
<p>This is a stream on top of the <em>Encrypted</em> stream that makes it possible to
read/write an encrypted data as a cleartext data.
</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>A ClearTextStream is the <code>clear</code> member of a SecurePair object.
</p>
<h3>Event: 'secureConnect'<span><a class="mark" href="#all_event_secureconnect" id="all_event_secureconnect">#</a></span></h3>
<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>cleartextStream.authorized</code>
to see if the server certificate was signed by one of the specified CAs.
If <code>cleartextStream.authorized === false</code> then the error can be found in
<code>cleartextStream.authorizationError</code>. Also if NPN was used - you can check
<code>cleartextStream.npnProtocol</code> for negotiated protocol.
</p>
<h3>cleartextStream.authorized<span><a class="mark" href="#all_cleartextstream_authorized" id="all_cleartextstream_authorized">#</a></span></h3>
<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>cleartextStream.authorizationError<span><a class="mark" href="#all_cleartextstream_authorizationerror" id="all_cleartextstream_authorizationerror">#</a></span></h3>
<p>The reason why the peer's certificate has not been verified. This property
becomes available only when <code>cleartextStream.authorized === false</code>.
</p>
<h3>cleartextStream.getPeerCertificate()<span><a class="mark" href="#all_cleartextstream_getpeercertificate" id="all_cleartextstream_getpeercertificate">#</a></span></h3>
<p>Returns an object representing the peer's certificate. The returned object has
some properties corresponding to the field of the certificate.
</p>
<p>Example:
</p>
<pre><code>{ subject:
{ C: 'UK',
ST: 'Acknack Ltd',
L: 'Rhys Jones',
O: 'node.js',
OU: 'Test TLS Certificate',
CN: 'localhost' },
issuer:
{ C: 'UK',
ST: 'Acknack Ltd',
L: 'Rhys Jones',
O: 'node.js',
OU: 'Test TLS Certificate',
CN: 'localhost' },
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' }</code></pre>
<p>If the peer does not provide a certificate, it returns <code>null</code> or an empty
object.
</p>
<h3>cleartextStream.getCipher()<span><a class="mark" href="#all_cleartextstream_getcipher" id="all_cleartextstream_getcipher">#</a></span></h3>
<p>Returns an object representing the cipher name and the SSL/TLS
protocol version of the current connection.
</p>
<p>Example:
{ name: 'AES256-SHA', version: 'TLSv1/SSLv3' }
</p>
<p>See SSL_CIPHER_get_name() and SSL_CIPHER_get_version() in
<a href="http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS">http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_CIPHERS</a> for more
information.
</p>
<h3>cleartextStream.address()<span><a class="mark" href="#all_cleartextstream_address" id="all_cleartextstream_address">#</a></span></h3>
<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>cleartextStream.remoteAddress<span><a class="mark" href="#all_cleartextstream_remoteaddress" id="all_cleartextstream_remoteaddress">#</a></span></h3>
<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>cleartextStream.remotePort<span><a class="mark" href="#all_cleartextstream_remoteport" id="all_cleartextstream_remoteport">#</a></span></h3>
<p>The numeric representation of the remote port. For example, <code>443</code>.
</p>
<h1>StringDecoder<span><a class="mark" href="#all_stringdecoder" id="all_stringdecoder">#</a></span></h1>
<pre class="api_stability_3">Stability: 3 - 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>var StringDecoder = require('string_decoder').StringDecoder;
var decoder = new StringDecoder('utf8');
var cent = new Buffer([0xC2, 0xA2]);
console.log(decoder.write(cent));
var euro = new Buffer([0xE2, 0x82, 0xAC]);
console.log(decoder.write(euro));</code></pre>
<h2>Class: StringDecoder<span><a class="mark" href="#all_class_stringdecoder" id="all_class_stringdecoder">#</a></span></h2>
<p>Accepts a single argument, <code>encoding</code> which defaults to <code>utf8</code>.
</p>
<h3>decoder.write(buffer)<span><a class="mark" href="#all_decoder_write_buffer" id="all_decoder_write_buffer">#</a></span></h3>
<p>Returns a decoded string.
</p>
<h3>decoder.end()<span><a class="mark" href="#all_decoder_end" id="all_decoder_end">#</a></span></h3>
<p>Returns any trailing bytes that were left in the buffer.
</p>
<h1>File System<span><a class="mark" href="#all_file_system" id="all_file_system">#</a></span></h1>
<pre class="api_stability_3">Stability: 3 - 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 take 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>var fs = require('fs');
fs.unlink('/tmp/hello', function (err) {
if (err) throw err;
console.log('successfully deleted /tmp/hello');
});</code></pre>
<p>Here is the synchronous version:
</p>
<pre><code>var 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>fs.rename('/tmp/hello', '/tmp/world', function (err) {
if (err) throw err;
console.log('renamed complete');
});
fs.stat('/tmp/world', function (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>fs.rename('/tmp/hello', '/tmp/world', function (err) {
if (err) throw err;
fs.stat('/tmp/world', function (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>Relative path to 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 ignores errors, but prints a deprecation
warning.
</p>
<p><strong>IMPORTANT</strong>: Omitting the callback is deprecated. v0.12 will throw the
errors as exceptions.
</p>
<h2>fs.rename(oldPath, newPath, callback)<span><a class="mark" href="#all_fs_rename_oldpath_newpath_callback" id="all_fs_rename_oldpath_newpath_callback">#</a></span></h2>
<p>Asynchronous rename(2). No arguments other than a possible exception are given
to the completion callback.
</p>
<h2>fs.renameSync(oldPath, newPath)<span><a class="mark" href="#all_fs_renamesync_oldpath_newpath" id="all_fs_renamesync_oldpath_newpath">#</a></span></h2>
<p>Synchronous rename(2).
</p>
<h2>fs.ftruncate(fd, len, callback)<span><a class="mark" href="#all_fs_ftruncate_fd_len_callback" id="all_fs_ftruncate_fd_len_callback">#</a></span></h2>
<p>Asynchronous ftruncate(2). No arguments other than a possible exception are
given to the completion callback.
</p>
<h2>fs.ftruncateSync(fd, len)<span><a class="mark" href="#all_fs_ftruncatesync_fd_len" id="all_fs_ftruncatesync_fd_len">#</a></span></h2>
<p>Synchronous ftruncate(2).
</p>
<h2>fs.truncate(path, len, callback)<span><a class="mark" href="#all_fs_truncate_path_len_callback" id="all_fs_truncate_path_len_callback">#</a></span></h2>
<p>Asynchronous truncate(2). No arguments other than a possible exception are
given to the completion callback.
</p>
<h2>fs.truncateSync(path, len)<span><a class="mark" href="#all_fs_truncatesync_path_len" id="all_fs_truncatesync_path_len">#</a></span></h2>
<p>Synchronous truncate(2).
</p>
<h2>fs.chown(path, uid, gid, callback)<span><a class="mark" href="#all_fs_chown_path_uid_gid_callback" id="all_fs_chown_path_uid_gid_callback">#</a></span></h2>
<p>Asynchronous chown(2). 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="#all_fs_chownsync_path_uid_gid" id="all_fs_chownsync_path_uid_gid">#</a></span></h2>
<p>Synchronous chown(2).
</p>
<h2>fs.fchown(fd, uid, gid, callback)<span><a class="mark" href="#all_fs_fchown_fd_uid_gid_callback" id="all_fs_fchown_fd_uid_gid_callback">#</a></span></h2>
<p>Asynchronous fchown(2). 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="#all_fs_fchownsync_fd_uid_gid" id="all_fs_fchownsync_fd_uid_gid">#</a></span></h2>
<p>Synchronous fchown(2).
</p>
<h2>fs.lchown(path, uid, gid, callback)<span><a class="mark" href="#all_fs_lchown_path_uid_gid_callback" id="all_fs_lchown_path_uid_gid_callback">#</a></span></h2>
<p>Asynchronous lchown(2). 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="#all_fs_lchownsync_path_uid_gid" id="all_fs_lchownsync_path_uid_gid">#</a></span></h2>
<p>Synchronous lchown(2).
</p>
<h2>fs.chmod(path, mode, callback)<span><a class="mark" href="#all_fs_chmod_path_mode_callback" id="all_fs_chmod_path_mode_callback">#</a></span></h2>
<p>Asynchronous chmod(2). No arguments other than a possible exception are given
to the completion callback.
</p>
<h2>fs.chmodSync(path, mode)<span><a class="mark" href="#all_fs_chmodsync_path_mode" id="all_fs_chmodsync_path_mode">#</a></span></h2>
<p>Synchronous chmod(2).
</p>
<h2>fs.fchmod(fd, mode, callback)<span><a class="mark" href="#all_fs_fchmod_fd_mode_callback" id="all_fs_fchmod_fd_mode_callback">#</a></span></h2>
<p>Asynchronous fchmod(2). No arguments other than a possible exception
are given to the completion callback.
</p>
<h2>fs.fchmodSync(fd, mode)<span><a class="mark" href="#all_fs_fchmodsync_fd_mode" id="all_fs_fchmodsync_fd_mode">#</a></span></h2>
<p>Synchronous fchmod(2).
</p>
<h2>fs.lchmod(path, mode, callback)<span><a class="mark" href="#all_fs_lchmod_path_mode_callback" id="all_fs_lchmod_path_mode_callback">#</a></span></h2>
<p>Asynchronous lchmod(2). 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="#all_fs_lchmodsync_path_mode" id="all_fs_lchmodsync_path_mode">#</a></span></h2>
<p>Synchronous lchmod(2).
</p>
<h2>fs.stat(path, callback)<span><a class="mark" href="#all_fs_stat_path_callback" id="all_fs_stat_path_callback">#</a></span></h2>
<p>Asynchronous stat(2). The callback gets two arguments <code>(err, stats)</code> where
<code>stats</code> is a <a href="#fs_class_fs_stats">fs.Stats</a> object. See the <a href="#fs_class_fs_stats">fs.Stats</a>
section below for more information.
</p>
<h2>fs.lstat(path, callback)<span><a class="mark" href="#all_fs_lstat_path_callback" id="all_fs_lstat_path_callback">#</a></span></h2>
<p>Asynchronous lstat(2). The callback gets two arguments <code>(err, stats)</code> where
<code>stats</code> is a <code>fs.Stats</code> 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.fstat(fd, callback)<span><a class="mark" href="#all_fs_fstat_fd_callback" id="all_fs_fstat_fd_callback">#</a></span></h2>
<p>Asynchronous fstat(2). The callback gets two arguments <code>(err, stats)</code> where
<code>stats</code> is a <code>fs.Stats</code> object. <code>fstat()</code> is identical to <code>stat()</code>, except that
the file to be stat-ed is specified by the file descriptor <code>fd</code>.
</p>
<h2>fs.statSync(path)<span><a class="mark" href="#all_fs_statsync_path" id="all_fs_statsync_path">#</a></span></h2>
<p>Synchronous stat(2). Returns an instance of <code>fs.Stats</code>.
</p>
<h2>fs.lstatSync(path)<span><a class="mark" href="#all_fs_lstatsync_path" id="all_fs_lstatsync_path">#</a></span></h2>
<p>Synchronous lstat(2). Returns an instance of <code>fs.Stats</code>.
</p>
<h2>fs.fstatSync(fd)<span><a class="mark" href="#all_fs_fstatsync_fd" id="all_fs_fstatsync_fd">#</a></span></h2>
<p>Synchronous fstat(2). Returns an instance of <code>fs.Stats</code>.
</p>
<h2>fs.link(srcpath, dstpath, callback)<span><a class="mark" href="#all_fs_link_srcpath_dstpath_callback" id="all_fs_link_srcpath_dstpath_callback">#</a></span></h2>
<p>Asynchronous link(2). No arguments other than a possible exception are given to
the completion callback.
</p>
<h2>fs.linkSync(srcpath, dstpath)<span><a class="mark" href="#all_fs_linksync_srcpath_dstpath" id="all_fs_linksync_srcpath_dstpath">#</a></span></h2>
<p>Synchronous link(2).
</p>
<h2>fs.symlink(srcpath, dstpath, [type], callback)<span><a class="mark" href="#all_fs_symlink_srcpath_dstpath_type_callback" id="all_fs_symlink_srcpath_dstpath_type_callback">#</a></span></h2>
<p>Asynchronous symlink(2). 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>destination</code> argument will automatically be normalized to absolute path.
</p>
<h2>fs.symlinkSync(srcpath, dstpath, [type])<span><a class="mark" href="#all_fs_symlinksync_srcpath_dstpath_type" id="all_fs_symlinksync_srcpath_dstpath_type">#</a></span></h2>
<p>Synchronous symlink(2).
</p>
<h2>fs.readlink(path, callback)<span><a class="mark" href="#all_fs_readlink_path_callback" id="all_fs_readlink_path_callback">#</a></span></h2>
<p>Asynchronous readlink(2). The callback gets two arguments <code>(err,
linkString)</code>.
</p>
<h2>fs.readlinkSync(path)<span><a class="mark" href="#all_fs_readlinksync_path" id="all_fs_readlinksync_path">#</a></span></h2>
<p>Synchronous readlink(2). Returns the symbolic link's string value.
</p>
<h2>fs.realpath(path, [cache], callback)<span><a class="mark" href="#all_fs_realpath_path_cache_callback" id="all_fs_realpath_path_cache_callback">#</a></span></h2>
<p>Asynchronous realpath(2). 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>var cache = {'/etc':'/private/etc'};
fs.realpath('/etc/passwd', cache, function (err, resolvedPath) {
if (err) throw err;
console.log(resolvedPath);
});</code></pre>
<h2>fs.realpathSync(path, [cache])<span><a class="mark" href="#all_fs_realpathsync_path_cache" id="all_fs_realpathsync_path_cache">#</a></span></h2>
<p>Synchronous realpath(2). Returns the resolved path.
</p>
<h2>fs.unlink(path, callback)<span><a class="mark" href="#all_fs_unlink_path_callback" id="all_fs_unlink_path_callback">#</a></span></h2>
<p>Asynchronous unlink(2). No arguments other than a possible exception are given
to the completion callback.
</p>
<h2>fs.unlinkSync(path)<span><a class="mark" href="#all_fs_unlinksync_path" id="all_fs_unlinksync_path">#</a></span></h2>
<p>Synchronous unlink(2).
</p>
<h2>fs.rmdir(path, callback)<span><a class="mark" href="#all_fs_rmdir_path_callback" id="all_fs_rmdir_path_callback">#</a></span></h2>
<p>Asynchronous rmdir(2). No arguments other than a possible exception are given
to the completion callback.
</p>
<h2>fs.rmdirSync(path)<span><a class="mark" href="#all_fs_rmdirsync_path" id="all_fs_rmdirsync_path">#</a></span></h2>
<p>Synchronous rmdir(2).
</p>
<h2>fs.mkdir(path, [mode], callback)<span><a class="mark" href="#all_fs_mkdir_path_mode_callback" id="all_fs_mkdir_path_mode_callback">#</a></span></h2>
<p>Asynchronous mkdir(2). No arguments other than a possible exception are given
to the completion callback. <code>mode</code> defaults to <code>0777</code>.
</p>
<h2>fs.mkdirSync(path, [mode])<span><a class="mark" href="#all_fs_mkdirsync_path_mode" id="all_fs_mkdirsync_path_mode">#</a></span></h2>
<p>Synchronous mkdir(2).
</p>
<h2>fs.readdir(path, callback)<span><a class="mark" href="#all_fs_readdir_path_callback" id="all_fs_readdir_path_callback">#</a></span></h2>
<p>Asynchronous readdir(3). 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="#all_fs_readdirsync_path" id="all_fs_readdirsync_path">#</a></span></h2>
<p>Synchronous readdir(3). Returns an array of filenames excluding <code>'.'</code> and
<code>'..'</code>.
</p>
<h2>fs.close(fd, callback)<span><a class="mark" href="#all_fs_close_fd_callback" id="all_fs_close_fd_callback">#</a></span></h2>
<p>Asynchronous close(2). No arguments other than a possible exception are given
to the completion callback.
</p>
<h2>fs.closeSync(fd)<span><a class="mark" href="#all_fs_closesync_fd" id="all_fs_closesync_fd">#</a></span></h2>
<p>Synchronous close(2).
</p>
<h2>fs.open(path, flags, [mode], callback)<span><a class="mark" href="#all_fs_open_path_flags_mode_callback" id="all_fs_open_path_flags_mode_callback">#</a></span></h2>
<p>Asynchronous file open. See open(2). <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 writeable.
</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 open(2)) 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>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="#all_fs_opensync_path_flags_mode" id="all_fs_opensync_path_flags_mode">#</a></span></h2>
<p>Synchronous version of <code>fs.open()</code>.
</p>
<h2>fs.utimes(path, atime, mtime, callback)<span><a class="mark" href="#all_fs_utimes_path_atime_mtime_callback" id="all_fs_utimes_path_atime_mtime_callback">#</a></span></h2>
<h2>fs.utimesSync(path, atime, mtime)<span><a class="mark" href="#all_fs_utimessync_path_atime_mtime" id="all_fs_utimessync_path_atime_mtime">#</a></span></h2>
<p>Change file timestamps of the file referenced by the supplied path.
</p>
<h2>fs.futimes(fd, atime, mtime, callback)<span><a class="mark" href="#all_fs_futimes_fd_atime_mtime_callback" id="all_fs_futimes_fd_atime_mtime_callback">#</a></span></h2>
<h2>fs.futimesSync(fd, atime, mtime)<span><a class="mark" href="#all_fs_futimessync_fd_atime_mtime" id="all_fs_futimessync_fd_atime_mtime">#</a></span></h2>
<p>Change the file timestamps of a file referenced by the supplied file
descriptor.
</p>
<h2>fs.fsync(fd, callback)<span><a class="mark" href="#all_fs_fsync_fd_callback" id="all_fs_fsync_fd_callback">#</a></span></h2>
<p>Asynchronous fsync(2). No arguments other than a possible exception are given
to the completion callback.
</p>
<h2>fs.fsyncSync(fd)<span><a class="mark" href="#all_fs_fsyncsync_fd" id="all_fs_fsyncsync_fd">#</a></span></h2>
<p>Synchronous fsync(2).
</p>
<h2>fs.write(fd, buffer, offset, length, position, callback)<span><a class="mark" href="#all_fs_write_fd_buffer_offset_length_position_callback" id="all_fs_write_fd_buffer_offset_length_position_callback">#</a></span></h2>
<p>Write <code>buffer</code> to the file specified by <code>fd</code>.
</p>
<p><code>offset</code> and <code>length</code> determine the part of the buffer to be written.
</p>
<p><code>position</code> refers to the offset from the beginning of the file where this data
should be written. If <code>position</code> is <code>null</code>, the data will be written at the
current position.
See pwrite(2).
</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.writeSync(fd, buffer, offset, length, position)<span><a class="mark" href="#all_fs_writesync_fd_buffer_offset_length_position" id="all_fs_writesync_fd_buffer_offset_length_position">#</a></span></h2>
<p>Synchronous version of <code>fs.write()</code>. Returns the number of bytes written.
</p>
<h2>fs.read(fd, buffer, offset, length, position, callback)<span><a class="mark" href="#all_fs_read_fd_buffer_offset_length_position_callback" id="all_fs_read_fd_buffer_offset_length_position_callback">#</a></span></h2>
<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.readSync(fd, buffer, offset, length, position)<span><a class="mark" href="#all_fs_readsync_fd_buffer_offset_length_position" id="all_fs_readsync_fd_buffer_offset_length_position">#</a></span></h2>
<p>Synchronous version of <code>fs.read</code>. Returns the number of <code>bytesRead</code>.
</p>
<h2>fs.readFile(filename, [options], callback)<span><a class="mark" href="#all_fs_readfile_filename_options_callback" id="all_fs_readfile_filename_options_callback">#</a></span></h2>
<div class="signature"><ul>
<li><code>filename</code> <span class="type">String</span></li>
<li><code>options</code> <span class="type">Object</span><ul>
<li><code>encoding</code> <span class="type">String | Null</span> default = <code>null</code></li>
<li><code>flag</code> <span class="type">String</span> default = <code>'r'</code></li>
</ul>
</li>
<li><code>callback</code> <span class="type">Function</span></li>
</div></ul>
<p>Asynchronously reads the entire contents of a file. Example:
</p>
<pre><code>fs.readFile('/etc/passwd', function (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>
<h2>fs.readFileSync(filename, [options])<span><a class="mark" href="#all_fs_readfilesync_filename_options" id="all_fs_readfilesync_filename_options">#</a></span></h2>
<p>Synchronous version of <code>fs.readFile</code>. Returns the contents of the <code>filename</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.writeFile(filename, data, [options], callback)<span><a class="mark" href="#all_fs_writefile_filename_data_options_callback" id="all_fs_writefile_filename_data_options_callback">#</a></span></h2>
<div class="signature"><ul>
<li><code>filename</code> <span class="type">String</span></li>
<li><code>data</code> <span class="type">String | Buffer</span></li>
<li><code>options</code> <span class="type">Object</span><ul>
<li><code>encoding</code> <span class="type">String | Null</span> default = <code>'utf8'</code></li>
<li><code>mode</code> <span class="type">Number</span> default = <code>438</code> (aka <code>0666</code> in Octal)</li>
<li><code>flag</code> <span class="type">String</span> default = <code>'w'</code></li>
</ul>
</li>
<li><code>callback</code> <span class="type">Function</span></li>
</div></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>fs.writeFile('message.txt', 'Hello Node', function (err) {
if (err) throw err;
console.log('It\'s saved!');
});</code></pre>
<h2>fs.writeFileSync(filename, data, [options])<span><a class="mark" href="#all_fs_writefilesync_filename_data_options" id="all_fs_writefilesync_filename_data_options">#</a></span></h2>
<p>The synchronous version of <code>fs.writeFile</code>.
</p>
<h2>fs.appendFile(filename, data, [options], callback)<span><a class="mark" href="#all_fs_appendfile_filename_data_options_callback" id="all_fs_appendfile_filename_data_options_callback">#</a></span></h2>
<div class="signature"><ul>
<li><code>filename</code> <span class="type">String</span></li>
<li><code>data</code> <span class="type">String | Buffer</span></li>
<li><code>options</code> <span class="type">Object</span><ul>
<li><code>encoding</code> <span class="type">String | Null</span> default = <code>'utf8'</code></li>
<li><code>mode</code> <span class="type">Number</span> default = <code>438</code> (aka <code>0666</code> in Octal)</li>
<li><code>flag</code> <span class="type">String</span> default = <code>'a'</code></li>
</ul>
</li>
<li><code>callback</code> <span class="type">Function</span></li>
</div></ul>
<p>Asynchronously append data to a file, creating the file if it not yet exists.
<code>data</code> can be a string or a buffer.
</p>
<p>Example:
</p>
<pre><code>fs.appendFile('message.txt', 'data to append', function (err) {
if (err) throw err;
console.log('The "data to append" was appended to file!');
});</code></pre>
<h2>fs.appendFileSync(filename, data, [options])<span><a class="mark" href="#all_fs_appendfilesync_filename_data_options" id="all_fs_appendfilesync_filename_data_options">#</a></span></h2>
<p>The synchronous version of <code>fs.appendFile</code>.
</p>
<h2>fs.watchFile(filename, [options], listener)<span><a class="mark" href="#all_fs_watchfile_filename_options_listener" id="all_fs_watchfile_filename_options_listener">#</a></span></h2>
<pre class="api_stability_2">Stability: 2 - Unstable. Use fs.watch instead, if possible.</pre><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 second argument is optional. The <code>options</code> if provided should be an object
containing two members a boolean, <code>persistent</code>, and <code>interval</code>. <code>persistent</code>
indicates whether the process should continue to run as long as files are
being watched. <code>interval</code> indicates 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>fs.watchFile('message.text', function (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>
<h2>fs.unwatchFile(filename, [listener])<span><a class="mark" href="#all_fs_unwatchfile_filename_listener" id="all_fs_unwatchfile_filename_listener">#</a></span></h2>
<pre class="api_stability_2">Stability: 2 - Unstable. Use fs.watch instead, if possible.</pre><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>
<h2>fs.watch(filename, [options], [listener])<span><a class="mark" href="#all_fs_watch_filename_options_listener" id="all_fs_watch_filename_options_listener">#</a></span></h2>
<pre class="api_stability_2">Stability: 2 - Unstable.</pre><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">fs.FSWatcher</a>.
</p>
<p>The second argument is optional. The <code>options</code> if provided should be an object
containing a boolean member <code>persistent</code>, which indicates whether the process
should continue to run as long as files are being watched. The default is
<code>{ persistent: true }</code>.
</p>
<p>The listener callback gets two arguments <code>(event, filename)</code>. <code>event</code> is either
'rename' or 'change', and <code>filename</code> is the name of the file which triggered
the event.
</p>
<h3>Caveats<span><a class="mark" href="#all_caveats" id="all_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>
<h4>Availability<span><a class="mark" href="#all_availability" id="all_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 (including OS X), this uses <code>kqueue</code>.</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>
</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 on network file systems (NFS, SMB, etc.) often doesn't work
reliably or at all.
</p>
<p>You can still use <code>fs.watchFile</code>, which uses stat polling, but it is slower and
less reliable.
</p>
<h4>Filename Argument<span><a class="mark" href="#all_filename_argument" id="all_filename_argument">#</a></span></h4>
<!--type=misc-->
<p>Providing <code>filename</code> argument in the callback is not supported
on every platform (currently it's 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>fs.watch('somedir', function (event, filename) {
console.log('event is: ' + event);
if (filename) {
console.log('filename provided: ' + filename);
} else {
console.log('filename not provided');
}
});</code></pre>
<h2>fs.exists(path, callback)<span><a class="mark" href="#all_fs_exists_path_callback" id="all_fs_exists_path_callback">#</a></span></h2>
<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>fs.exists('/etc/passwd', function (exists) {
util.debug(exists ? "it's there" : "no passwd!");
});</code></pre>
<p><code>fs.exists()</code> is an anachronism and exists only for historical reasons.
There should almost never be a reason to use it in your own code.
</p>
<p>In particular, checking if a file exists before opening it is an anti-pattern
that leaves you vulnerable to race conditions: another process may remove the
file between the calls to <code>fs.exists()</code> and <code>fs.open()</code>. Just open the file
and handle the error when it's not there.
</p>
<h2>fs.existsSync(path)<span><a class="mark" href="#all_fs_existssync_path" id="all_fs_existssync_path">#</a></span></h2>
<p>Synchronous version of <code>fs.exists</code>.
</p>
<h2>Class: fs.Stats<span><a class="mark" href="#all_class_fs_stats" id="all_class_fs_stats">#</a></span></h2>
<p>Objects returned from <code>fs.stat()</code>, <code>fs.lstat()</code> and <code>fs.fstat()</code> 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 <code>fs.lstat()</code>)</li>
<li><code>stats.isFIFO()</code></li>
<li><code>stats.isSocket()</code></li>
</ul>
<p>For a regular file <code>util.inspect(stats)</code> would return a string very
similar to this:
</p>
<pre><code>{ 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 }</code></pre>
<p>Please note that <code>atime</code>, <code>mtime</code> and <code>ctime</code> are instances
of <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date">Date</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">getTime()</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 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>
<h2>fs.createReadStream(path, [options])<span><a class="mark" href="#all_fs_createreadstream_path_options" id="all_fs_createreadstream_path_options">#</a></span></h2>
<p>Returns a new ReadStream object (See <code>Readable Stream</code>).
</p>
<p><code>options</code> is an object with the following defaults:
</p>
<pre><code>{ flags: 'r',
encoding: null,
fd: null,
mode: 0666,
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 at 0. The <code>encoding</code> can be <code>'utf8'</code>, <code>'ascii'</code>, or <code>'base64'</code>.
</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 responsiblity to close it and make sure
there's no file descriptor leak. If <code>autoClose</code> is set to true (default
behavior), on <code>error</code> or <code>end</code> the file descriptor will be closed
automatically.
</p>
<p>An example to read the last 10 bytes of a file which is 100 bytes long:
</p>
<pre><code>fs.createReadStream('sample.txt', {start: 90, end: 99});</code></pre>
<h2>Class: fs.ReadStream<span><a class="mark" href="#all_class_fs_readstream" id="all_class_fs_readstream">#</a></span></h2>
<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="#all_event_open" id="all_event_open">#</a></span></h3>
<div class="signature"><ul>
<li><code>fd</code> <span class="type">Integer</span> file descriptor used by the ReadStream.</li>
</div></ul>
<p>Emitted when the ReadStream's file is opened.
</p>
<h2>fs.createWriteStream(path, [options])<span><a class="mark" href="#all_fs_createwritestream_path_options" id="all_fs_createwritestream_path_options">#</a></span></h2>
<p>Returns a new WriteStream object (See <code>Writable Stream</code>).
</p>
<p><code>options</code> is an object with the following defaults:
</p>
<pre><code>{ flags: 'w',
encoding: null,
mode: 0666 }</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>.
</p>
<h2>Class: fs.WriteStream<span><a class="mark" href="#all_class_fs_writestream" id="all_class_fs_writestream">#</a></span></h2>
<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="#all_event_open_1" id="all_event_open_1">#</a></span></h3>
<div class="signature"><ul>
<li><code>fd</code> <span class="type">Integer</span> file descriptor used by the WriteStream.</li>
</div></ul>
<p>Emitted when the WriteStream's file is opened.
</p>
<h3>file.bytesWritten<span><a class="mark" href="#all_file_byteswritten" id="all_file_byteswritten">#</a></span></h3>
<p>The number of bytes written so far. Does not include data that is still queued
for writing.
</p>
<h2>Class: fs.FSWatcher<span><a class="mark" href="#all_class_fs_fswatcher" id="all_class_fs_fswatcher">#</a></span></h2>
<p>Objects returned from <code>fs.watch()</code> are of this type.
</p>
<h3>watcher.close()<span><a class="mark" href="#all_watcher_close" id="all_watcher_close">#</a></span></h3>
<p>Stop watching for changes on the given <code>fs.FSWatcher</code>.
</p>
<h3>Event: 'change'<span><a class="mark" href="#all_event_change" id="all_event_change">#</a></span></h3>
<div class="signature"><ul>
<li><code>event</code> <span class="type">String</span> The type of fs change</li>
<li><code>filename</code> <span class="type">String</span> The filename that changed (if relevant/available)</li>
</div></ul>
<p>Emitted when something changes in a watched directory or file.
See more details in <a href="#fs_fs_watch_filename_options_listener">fs.watch</a>.
</p>
<h3>Event: 'error'<span><a class="mark" href="#all_event_error_2" id="all_event_error_2">#</a></span></h3>
<div class="signature"><ul>
<li><code>error</code> <span class="type">Error object</span></li>
</div></ul>
<p>Emitted when an error occurs.
</p>
<h1>Path<span><a class="mark" href="#all_path" id="all_path">#</a></span></h1>
<pre class="api_stability_3">Stability: 3 - 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.normalize(p)<span><a class="mark" href="#all_path_normalize_p" id="all_path_normalize_p">#</a></span></h2>
<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>path.normalize('/foo/bar//baz/asdf/quux/..')
// returns
'/foo/bar/baz/asdf'</code></pre>
<h2>path.join([path1], [path2], [...])<span><a class="mark" href="#all_path_join_path1_path2" id="all_path_join_path1_path2">#</a></span></h2>
<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>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>
<h2>path.resolve([from ...], to)<span><a class="mark" href="#all_path_resolve_from_to" id="all_path_resolve_from_to">#</a></span></h2>
<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 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>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>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>
<h2>path.relative(from, to)<span><a class="mark" href="#all_path_relative_from_to" id="all_path_relative_from_to">#</a></span></h2>
<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>path.resolve(from, path.relative(from, to)) == path.resolve(to)</code></pre>
<p>Examples:
</p>
<pre><code>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>
<h2>path.dirname(p)<span><a class="mark" href="#all_path_dirname_p" id="all_path_dirname_p">#</a></span></h2>
<p>Return the directory name of a path. Similar to the Unix <code>dirname</code> command.
</p>
<p>Example:
</p>
<pre><code>path.dirname('/foo/bar/baz/asdf/quux')
// returns
'/foo/bar/baz/asdf'</code></pre>
<h2>path.basename(p, [ext])<span><a class="mark" href="#all_path_basename_p_ext" id="all_path_basename_p_ext">#</a></span></h2>
<p>Return the last portion of a path. Similar to the Unix <code>basename</code> command.
</p>
<p>Example:
</p>
<pre><code>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.extname(p)<span><a class="mark" href="#all_path_extname_p" id="all_path_extname_p">#</a></span></h2>
<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>path.extname('index.html')
// returns
'.html'
path.extname('index.coffee.md')
// returns
'.md'
path.extname('index.')
// returns
'.'
path.extname('index')
// returns
''</code></pre>
<h2>path.sep<span><a class="mark" href="#all_path_sep" id="all_path_sep">#</a></span></h2>
<p>The platform-specific file separator. <code>'\\'</code> or <code>'/'</code>.
</p>
<p>An example on *nix:
</p>
<pre><code>'foo/bar/baz'.split(path.sep)
// returns
['foo', 'bar', 'baz']</code></pre>
<p>An example on Windows:
</p>
<pre><code>'foo\\bar\\baz'.split(path.sep)
// returns
['foo', 'bar', 'baz']</code></pre>
<h2>path.delimiter<span><a class="mark" href="#all_path_delimiter" id="all_path_delimiter">#</a></span></h2>
<p>The platform-specific path delimiter, <code>;</code> or <code>':'</code>.
</p>
<p>An example on *nix:
</p>
<pre><code>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>console.log(process.env.PATH)
// 'C:\Windows\system32;C:\Windows;C:\Program Files\nodejs\'
process.env.PATH.split(path.delimiter)
// returns
['C:\Windows\system32', 'C:\Windows', 'C:\Program Files\nodejs\']</code></pre>
<h1>net<span><a class="mark" href="#all_net" id="all_net">#</a></span></h1>
<pre class="api_stability_3">Stability: 3 - Stable</pre><p>The <code>net</code> module provides you with an asynchronous network wrapper. It contains
methods for creating both servers and clients (called streams). You can include
this module with <code>require('net');</code>
</p>
<h2>net.createServer([options], [connectionListener])<span><a class="mark" href="#all_net_createserver_options_connectionlistener" id="all_net_createserver_options_connectionlistener">#</a></span></h2>
<p>Creates a new TCP server. The <code>connectionListener</code> argument is
automatically set as a listener for the <a href="#net_event_connection">'connection'</a> event.
</p>
<p><code>options</code> is an object with the following defaults:
</p>
<pre><code>{ allowHalfOpen: 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 <code>end()</code> method explicitly.
See <a href="#net_event_end">'end'</a> event for more information.
</p>
<p>Here is an example of an echo server which listens for connections
on port 8124:
</p>
<pre><code>var net = require('net');
var server = net.createServer(function(c) { //'connection' listener
console.log('server connected');
c.on('end', function() {
console.log('server disconnected');
});
c.write('hello\r\n');
c.pipe(c);
});
server.listen(8124, function() { //'listening' listener
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>server.listen('/tmp/echo.sock', function() { //'listening' listener</code></pre>
<p>Use <code>nc</code> to connect to a UNIX domain socket server:
</p>
<pre><code>nc -U /tmp/echo.sock</code></pre>
<h2>net.connect(options, [connectionListener])<span><a class="mark" href="#all_net_connect_options_connectionlistener" id="all_net_connect_options_connectionlistener">#</a></span></h2>
<h2>net.createConnection(options, [connectionListener])<span><a class="mark" href="#all_net_createconnection_options_connectionlistener" id="all_net_createconnection_options_connectionlistener">#</a></span></h2>
<p>Constructs a new socket object and opens the socket to the given location.
When the socket is established, the <a href="#net_event_connect">'connect'</a> event will be emitted.
</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>
</ul>
<p>For UNIX 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>Common options are:
</p>
<ul>
<li><code>allowHalfOpen</code>: if <code>true</code>, the socket won't automatically send
a FIN packet when the other end of the socket sends a FIN packet.
Defaults to <code>false</code>. See <a href="#net_event_end">'end'</a> event for more information.</li>
</ul>
<p>The <code>connectListener</code> parameter will be added as an listener for the
<a href="#net_event_connect">'connect'</a> event.
</p>
<p>Here is an example of a client of echo server as described previously:
</p>
<pre><code>var net = require('net');
var client = net.connect({port: 8124},
function() { //'connect' listener
console.log('client connected');
client.write('world!\r\n');
});
client.on('data', function(data) {
console.log(data.toString());
client.end();
});
client.on('end', function() {
console.log('client disconnected');
});</code></pre>
<p>To connect on the socket <code>/tmp/echo.sock</code> the second line would just be
changed to
</p>
<pre><code>var client = net.connect({path: '/tmp/echo.sock'});</code></pre>
<h2>net.connect(port, [host], [connectListener])<span><a class="mark" href="#all_net_connect_port_host_connectlistener" id="all_net_connect_port_host_connectlistener">#</a></span></h2>
<h2>net.createConnection(port, [host], [connectListener])<span><a class="mark" href="#all_net_createconnection_port_host_connectlistener" id="all_net_createconnection_port_host_connectlistener">#</a></span></h2>
<p>Creates a TCP connection to <code>port</code> on <code>host</code>. If <code>host</code> is omitted,
<code>'localhost'</code> will be assumed.
The <code>connectListener</code> parameter will be added as an listener for the
<a href="#net_event_connect">'connect'</a> event.
</p>
<h2>net.connect(path, [connectListener])<span><a class="mark" href="#all_net_connect_path_connectlistener" id="all_net_connect_path_connectlistener">#</a></span></h2>
<h2>net.createConnection(path, [connectListener])<span><a class="mark" href="#all_net_createconnection_path_connectlistener" id="all_net_createconnection_path_connectlistener">#</a></span></h2>
<p>Creates unix socket connection to <code>path</code>.
The <code>connectListener</code> parameter will be added as an listener for the
<a href="#net_event_connect">'connect'</a> event.
</p>
<h2>Class: net.Server<span><a class="mark" href="#all_class_net_server" id="all_class_net_server">#</a></span></h2>
<p>This class is used to create a TCP or UNIX server.
</p>
<h3>server.listen(port, [host], [backlog], [callback])<span><a class="mark" href="#all_server_listen_port_host_backlog_callback" id="all_server_listen_port_host_backlog_callback">#</a></span></h3>
<p>Begin accepting connections on the specified <code>port</code> and <code>host</code>. If the
<code>host</code> is omitted, the server will accept connections directed to any
IPv4 address (<code>INADDR_ANY</code>). A port value of zero will assign a random port.
</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. When the server has been bound,
<a href="net.html#net_event_listening">'listening'</a> event will be emitted. The last parameter <code>callback</code>
will be added as an listener for the <a href="net.html#net_event_listening">'listening'</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. This can be done with
</p>
<pre><code>server.on('error', function (e) {
if (e.code == 'EADDRINUSE') {
console.log('Address in use, retrying...');
setTimeout(function () {
server.close();
server.listen(PORT, HOST);
}, 1000);
}
});</code></pre>
<p>(Note: All sockets in Node set <code>SO_REUSEADDR</code> already)
</p>
<h3>server.listen(path, [callback])<span><a class="mark" href="#all_server_listen_path_callback" id="all_server_listen_path_callback">#</a></span></h3>
<p>Start a UNIX 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.html#net_event_listening">'listening'</a> event will be emitted. The last parameter <code>callback</code>
will be added as an listener for the <a href="net.html#net_event_listening">'listening'</a> event.
</p>
<h3>server.listen(handle, [callback])<span><a class="mark" href="#all_server_listen_handle_callback" id="all_server_listen_handle_callback">#</a></span></h3>
<div class="signature"><ul>
<li><code>handle</code> <span class="type">Object</span></li>
<li><code>callback</code> <span class="type">Function</span></li>
</div></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="#event_listening_">'listening'</a> event will be emitted.
the last parameter <code>callback</code> will be added as an listener for the
<a href="#event_listening_">'listening'</a> event.
</p>
<h3>server.close([callback])<span><a class="mark" href="#all_server_close_callback" id="all_server_close_callback">#</a></span></h3>
<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 <code>'close'</code>
event. Optionally, you can pass a callback to listen for the <code>'close'</code>
event.
</p>
<h3>server.address()<span><a class="mark" href="#all_server_address_1" id="all_server_address_1">#</a></span></h3>
<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 giving getting an OS-assigned address.
Returns an object with three properties, e.g.
<code>{ port: 12346, family: 'IPv4', address: '127.0.0.1' }</code>
</p>
<p>Example:
</p>
<pre><code>var server = net.createServer(function (socket) {
socket.end("goodbye\n");
});
// grab a random port.
server.listen(function() {
address = server.address();
console.log("opened server on %j", address);
});</code></pre>
<p>Don't call <code>server.address()</code> until the <code>'listening'</code> event has been emitted.
</p>
<h3>server.unref()<span><a class="mark" href="#all_server_unref" id="all_server_unref">#</a></span></h3>
<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>
<h3>server.ref()<span><a class="mark" href="#all_server_ref" id="all_server_ref">#</a></span></h3>
<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>
<h3>server.maxConnections<span><a class="mark" href="#all_server_maxconnections_1" id="all_server_maxconnections_1">#</a></span></h3>
<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 <code>child_process.fork()</code>.
</p>
<h3>server.connections<span><a class="mark" href="#all_server_connections_1" id="all_server_connections_1">#</a></span></h3>
<p>This function is <strong>deprecated</strong>; please use <a href="#net_server_getconnections_callback">server.getConnections()</a> instead.
The number of concurrent connections on the server.
</p>
<p>This becomes <code>null</code> when sending a socket to a child with
<code>child_process.fork()</code>. 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="#all_server_getconnections_callback" id="all_server_getconnections_callback">#</a></span></h3>
<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>
<p><code>net.Server</code> is an <a href="events.html#events_class_events_eventemitter">EventEmitter</a> with the following events:
</p>
<h3>Event: 'listening'<span><a class="mark" href="#all_event_listening" id="all_event_listening">#</a></span></h3>
<p>Emitted when the server has been bound after calling <code>server.listen</code>.
</p>
<h3>Event: 'connection'<span><a class="mark" href="#all_event_connection" id="all_event_connection">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">Socket object</span> The connection object</li>
</div></ul>
<p>Emitted when a new connection is made. <code>socket</code> is an instance of
<code>net.Socket</code>.
</p>
<h3>Event: 'close'<span><a class="mark" href="#all_event_close_1" id="all_event_close_1">#</a></span></h3>
<p>Emitted when the server closes. Note that if connections exist, this
event is not emitted until all connections are ended.
</p>
<h3>Event: 'error'<span><a class="mark" href="#all_event_error_3" id="all_event_error_3">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">Error Object</span></li>
</div></ul>
<p>Emitted when an error occurs. The <code>'close'</code> event will be called directly
following this event. See example in discussion of <code>server.listen</code>.
</p>
<h2>Class: net.Socket<span><a class="mark" href="#all_class_net_socket" id="all_class_net_socket">#</a></span></h2>
<p>This object is an abstraction of a TCP or UNIX socket. <code>net.Socket</code>
instances implement a duplex Stream interface. They can be created by the
user and used as a client (with <code>connect()</code>) or they can be created by Node
and passed to the user through the <code>'connection'</code> event of a server.
</p>
<h3>new net.Socket([options])<span><a class="mark" href="#all_new_net_socket_options" id="all_new_net_socket_options">#</a></span></h3>
<p>Construct a new socket object.
</p>
<p><code>options</code> is an object with the following defaults:
</p>
<pre><code>{ 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>
<h3>socket.connect(port, [host], [connectListener])<span><a class="mark" href="#all_socket_connect_port_host_connectlistener" id="all_socket_connect_port_host_connectlistener">#</a></span></h3>
<h3>socket.connect(path, [connectListener])<span><a class="mark" href="#all_socket_connect_path_connectlistener" id="all_socket_connect_path_connectlistener">#</a></span></h3>
<p>Opens the connection for a given socket. If <code>port</code> and <code>host</code> are given,
then the socket will be opened as a TCP socket, if <code>host</code> is omitted,
<code>localhost</code> will be assumed. If a <code>path</code> is given, the socket will be
opened as a unix socket to that path.
</p>
<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">'connect'</a> event is emitted the
socket is established. If there is a problem connecting, the <code>'connect'</code> event
will not be emitted, the <code>'error'</code> event will be emitted with the exception.
</p>
<p>The <code>connectListener</code> parameter will be added as an listener for the
<a href="#net_event_connect">'connect'</a> event.
</p>
<h3>socket.bufferSize<span><a class="mark" href="#all_socket_buffersize" id="all_socket_buffersize">#</a></span></h3>
<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 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 <code>pause()</code> and <code>resume()</code>.
</p>
<h3>socket.setEncoding([encoding])<span><a class="mark" href="#all_socket_setencoding_encoding" id="all_socket_setencoding_encoding">#</a></span></h3>
<p>Set the encoding for the socket as a Readable Stream. See
<a href="stream.html#stream_stream_setencoding_encoding">stream.setEncoding()</a> for more information.
</p>
<h3>socket.write(data, [encoding], [callback])<span><a class="mark" href="#all_socket_write_data_encoding_callback" id="all_socket_write_data_encoding_callback">#</a></span></h3>
<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.
<code>'drain'</code> 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>
<h3>socket.end([data], [encoding])<span><a class="mark" href="#all_socket_end_data_encoding" id="all_socket_end_data_encoding">#</a></span></h3>
<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.destroy()<span><a class="mark" href="#all_socket_destroy" id="all_socket_destroy">#</a></span></h3>
<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.pause()<span><a class="mark" href="#all_socket_pause" id="all_socket_pause">#</a></span></h3>
<p>Pauses the reading of data. That is, <code>'data'</code> events will not be emitted.
Useful to throttle back an upload.
</p>
<h3>socket.resume()<span><a class="mark" href="#all_socket_resume" id="all_socket_resume">#</a></span></h3>
<p>Resumes reading after a call to <code>pause()</code>.
</p>
<h3>socket.setTimeout(timeout, [callback])<span><a class="mark" href="#all_socket_settimeout_timeout_callback" id="all_socket_settimeout_timeout_callback">#</a></span></h3>
<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 <code>'timeout'</code>
event but the connection will not be severed. The user must manually <code>end()</code>
or <code>destroy()</code> 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
<code>'timeout'</code> event.
</p>
<h3>socket.setNoDelay([noDelay])<span><a class="mark" href="#all_socket_setnodelay_nodelay" id="all_socket_setnodelay_nodelay">#</a></span></h3>
<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>
<h3>socket.setKeepAlive([enable], [initialDelay])<span><a class="mark" href="#all_socket_setkeepalive_enable_initialdelay" id="all_socket_setkeepalive_enable_initialdelay">#</a></span></h3>
<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>
<h3>socket.address()<span><a class="mark" href="#all_socket_address" id="all_socket_address">#</a></span></h3>
<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.unref()<span><a class="mark" href="#all_socket_unref" id="all_socket_unref">#</a></span></h3>
<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>
<h3>socket.ref()<span><a class="mark" href="#all_socket_ref" id="all_socket_ref">#</a></span></h3>
<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>
<h3>socket.remoteAddress<span><a class="mark" href="#all_socket_remoteaddress" id="all_socket_remoteaddress">#</a></span></h3>
<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>socket.remotePort<span><a class="mark" href="#all_socket_remoteport" id="all_socket_remoteport">#</a></span></h3>
<p>The numeric representation of the remote port. For example,
<code>80</code> or <code>21</code>.
</p>
<h3>socket.localAddress<span><a class="mark" href="#all_socket_localaddress" id="all_socket_localaddress">#</a></span></h3>
<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="#all_socket_localport" id="all_socket_localport">#</a></span></h3>
<p>The numeric representation of the local port. For example,
<code>80</code> or <code>21</code>.
</p>
<h3>socket.bytesRead<span><a class="mark" href="#all_socket_bytesread" id="all_socket_bytesread">#</a></span></h3>
<p>The amount of received bytes.
</p>
<h3>socket.bytesWritten<span><a class="mark" href="#all_socket_byteswritten" id="all_socket_byteswritten">#</a></span></h3>
<p>The amount of bytes sent.
</p>
<p><code>net.Socket</code> instances are <a href="events.html#events_class_events_eventemitter">EventEmitter</a> with the following events:
</p>
<h3>Event: 'connect'<span><a class="mark" href="#all_event_connect" id="all_event_connect">#</a></span></h3>
<p>Emitted when a socket connection is successfully established.
See <code>connect()</code>.
</p>
<h3>Event: 'data'<span><a class="mark" href="#all_event_data_1" id="all_event_data_1">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">Buffer object</span></li>
</div></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: 'end'<span><a class="mark" href="#all_event_end_1" id="all_event_end_1">#</a></span></h3>
<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: 'timeout'<span><a class="mark" href="#all_event_timeout" id="all_event_timeout">#</a></span></h3>
<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: <code>socket.setTimeout()</code>
</p>
<h3>Event: 'drain'<span><a class="mark" href="#all_event_drain_1" id="all_event_drain_1">#</a></span></h3>
<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: 'error'<span><a class="mark" href="#all_event_error_4" id="all_event_error_4">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">Error object</span></li>
</div></ul>
<p>Emitted when an error occurs. The <code>'close'</code> event will be called directly
following this event.
</p>
<h3>Event: 'close'<span><a class="mark" href="#all_event_close_2" id="all_event_close_2">#</a></span></h3>
<div class="signature"><ul>
<li><code>had_error</code> <span class="type">Boolean</span> true if the socket had a transmission error</li>
</div></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>
<h2>net.isIP(input)<span><a class="mark" href="#all_net_isip_input" id="all_net_isip_input">#</a></span></h2>
<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="#all_net_isipv4_input" id="all_net_isipv4_input">#</a></span></h2>
<p>Returns true if input is a version 4 IP address, otherwise returns false.
</p>
<h2>net.isIPv6(input)<span><a class="mark" href="#all_net_isipv6_input" id="all_net_isipv6_input">#</a></span></h2>
<p>Returns true if input is a version 6 IP address, otherwise returns false.
</p>
<h1>UDP / Datagram Sockets<span><a class="mark" href="#all_udp_datagram_sockets" id="all_udp_datagram_sockets">#</a></span></h1>
<pre class="api_stability_3">Stability: 3 - Stable</pre><!-- name=dgram -->
<p>Datagram sockets are available through <code>require('dgram')</code>.
</p>
<p>Important note: the behavior of <code>dgram.Socket#bind()</code> has changed in v0.10
and is always asynchronous now. If you have code that looks like this:
</p>
<pre><code>var s = dgram.createSocket('udp4');
s.bind(1234);
s.addMembership('224.0.0.114');</code></pre>
<p>You have to change it to this:
</p>
<pre><code>var s = dgram.createSocket('udp4');
s.bind(1234, function() {
s.addMembership('224.0.0.114');
});</code></pre>
<h2>dgram.createSocket(type, [callback])<span><a class="mark" href="#all_dgram_createsocket_type_callback" id="all_dgram_createsocket_type_callback">#</a></span></h2>
<div class="signature"><ul>
<li><code>type</code> String. Either 'udp4' or 'udp6'</li>
<li><code>callback</code> Function. Attached as a listener to <code>message</code> events.
Optional</li>
<li>Returns: Socket object</li>
</div></ul>
<p>Creates a datagram Socket of the specified types. Valid types are <code>udp4</code>
and <code>udp6</code>.
</p>
<p>Takes an optional callback which is added as a listener for <code>message</code> events.
</p>
<p>Call <code>socket.bind</code> if you want to receive datagrams. <code>socket.bind()</code> will bind
to the "all interfaces" address on a random port (it does the right thing for
both <code>udp4</code> and <code>udp6</code> sockets). You can then retrieve the address and port
with <code>socket.address().address</code> and <code>socket.address().port</code>.
</p>
<h2>Class: dgram.Socket<span><a class="mark" href="#all_class_dgram_socket" id="all_class_dgram_socket">#</a></span></h2>
<p>The dgram Socket class encapsulates the datagram functionality. It
should be created via <code>dgram.createSocket(type, [callback])</code>.
</p>
<h3>Event: 'message'<span><a class="mark" href="#all_event_message" id="all_event_message">#</a></span></h3>
<div class="signature"><ul>
<li><code>msg</code> Buffer object. The message</li>
<li><code>rinfo</code> Object. Remote address information</li>
</div></ul>
<p>Emitted when a new datagram is available on a socket. <code>msg</code> is a <code>Buffer</code> and <code>rinfo</code> is
an object with the sender's address information and the number of bytes in the datagram.
</p>
<h3>Event: 'listening'<span><a class="mark" href="#all_event_listening_1" id="all_event_listening_1">#</a></span></h3>
<p>Emitted when a socket starts listening for datagrams. This happens as soon as UDP sockets
are created.
</p>
<h3>Event: 'close'<span><a class="mark" href="#all_event_close_3" id="all_event_close_3">#</a></span></h3>
<p>Emitted when a socket is closed with <code>close()</code>. No new <code>message</code> events will be emitted
on this socket.
</p>
<h3>Event: 'error'<span><a class="mark" href="#all_event_error_5" id="all_event_error_5">#</a></span></h3>
<div class="signature"><ul>
<li><code>exception</code> Error object</li>
</div></ul>
<p>Emitted when an error occurs.
</p>
<h3>socket.send(buf, offset, length, port, address, [callback])<span><a class="mark" href="#all_socket_send_buf_offset_length_port_address_callback" id="all_socket_send_buf_offset_length_port_address_callback">#</a></span></h3>
<div class="signature"><ul>
<li><code>buf</code> Buffer object. Message to be sent</li>
<li><code>offset</code> Integer. Offset in the buffer where the message starts.</li>
<li><code>length</code> Integer. Number of bytes in the message.</li>
<li><code>port</code> Integer. Destination port.</li>
<li><code>address</code> String. Destination hostname or IP address.</li>
<li><code>callback</code> Function. Called when the message has been sent. Optional.</li>
</div></ul>
<p>For UDP sockets, the destination port and address must be specified. A string
may be supplied for the <code>address</code> parameter, and it will be resolved with DNS.
</p>
<p>If the address is omitted or is an empty string, <code>'0.0.0.0'</code> or <code>'::0'</code> is used
instead. Depending on the network configuration, those defaults may or may not
work; it's 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>, it gets
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 callback may be specified to detect DNS errors or for determining
when it's safe to reuse the <code>buf</code> object. Note that DNS lookups delay the time
to send for at least one tick. The only way to know for sure that the datagram
has been sent is by using a callback.
</p>
<p>Example of sending a UDP packet to a random port on <code>localhost</code>;
</p>
<pre><code>var dgram = require('dgram');
var message = new Buffer("Some bytes");
var client = dgram.createSocket("udp4");
client.send(message, 0, message.length, 41234, "localhost", function(err, bytes) {
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
cannot be larger than 64K octets including 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 datagrams
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 datagrams.
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 have
a minimum <code>MTU</code> of <code>1500</code> (like Ethernet).</p>
</li>
</ul>
<p>Note that it's impossible to know in advance the MTU of each link through which
a packet might travel, and that generally sending a datagram greater than
the (receiver) <code>MTU</code> won't work (the packet gets silently dropped, without
informing the source that the data did not reach its intended recipient).
</p>
<h3>socket.bind(port, [address], [callback])<span><a class="mark" href="#all_socket_bind_port_address_callback" id="all_socket_bind_port_address_callback">#</a></span></h3>
<div class="signature"><ul>
<li><code>port</code> Integer</li>
<li><code>address</code> String, Optional</li>
<li><code>callback</code> Function with no parameters, Optional. Callback when
binding is done.</li>
</div></ul>
<p>For UDP sockets, listen for datagrams on a named <code>port</code> and optional
<code>address</code>. If <code>address</code> is not specified, the OS will try to listen on
all addresses. After binding is done, a "listening" event is emitted
and the <code>callback</code>(if specified) is called. Specifying both a
"listening" event listener and <code>callback</code> is not harmful but not very
useful.
</p>
<p>A bound datagram socket keeps the node process running to receive
datagrams.
</p>
<p>If binding fails, an "error" event is generated. In rare case (e.g.
binding a closed socket), an <code>Error</code> may be thrown by this method.
</p>
<p>Example of a UDP server listening on port 41234:
</p>
<pre><code>var dgram = require("dgram");
var server = dgram.createSocket("udp4");
server.on("error", function (err) {
console.log("server error:\n" + err.stack);
server.close();
});
server.on("message", function (msg, rinfo) {
console.log("server got: " + msg + " from " +
rinfo.address + ":" + rinfo.port);
});
server.on("listening", function () {
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.close()<span><a class="mark" href="#all_socket_close" id="all_socket_close">#</a></span></h3>
<p>Close the underlying socket and stop listening for data on it.
</p>
<h3>socket.address()<span><a class="mark" href="#all_socket_address_1" id="all_socket_address_1">#</a></span></h3>
<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>.
</p>
<h3>socket.setBroadcast(flag)<span><a class="mark" href="#all_socket_setbroadcast_flag" id="all_socket_setbroadcast_flag">#</a></span></h3>
<div class="signature"><ul>
<li><code>flag</code> Boolean</li>
</div></ul>
<p>Sets or clears the <code>SO_BROADCAST</code> socket option. When this option is set, UDP packets
may be sent to a local interface's broadcast address.
</p>
<h3>socket.setTTL(ttl)<span><a class="mark" href="#all_socket_setttl_ttl" id="all_socket_setttl_ttl">#</a></span></h3>
<div class="signature"><ul>
<li><code>ttl</code> Integer</li>
</div></ul>
<p>Sets the <code>IP_TTL</code> socket option. TTL stands for "Time to Live," but in this context it
specifies the number of IP hops that a packet is allowed to go 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>setTTL()</code> is a number of hops between 1 and 255. The default on most
systems is 64.
</p>
<h3>socket.setMulticastTTL(ttl)<span><a class="mark" href="#all_socket_setmulticastttl_ttl" id="all_socket_setmulticastttl_ttl">#</a></span></h3>
<div class="signature"><ul>
<li><code>ttl</code> Integer</li>
</div></ul>
<p>Sets the <code>IP_MULTICAST_TTL</code> socket option. TTL stands for "Time to Live," but in this
context it specifies the number of IP hops that a packet is allowed to go 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 to <code>setMulticastTTL()</code> is a number of hops between 0 and 255. The default on most
systems is 1.
</p>
<h3>socket.setMulticastLoopback(flag)<span><a class="mark" href="#all_socket_setmulticastloopback_flag" id="all_socket_setmulticastloopback_flag">#</a></span></h3>
<div class="signature"><ul>
<li><code>flag</code> Boolean</li>
</div></ul>
<p>Sets or clears the <code>IP_MULTICAST_LOOP</code> socket option. When this option is set, multicast
packets will also be received on the local interface.
</p>
<h3>socket.addMembership(multicastAddress, [multicastInterface])<span><a class="mark" href="#all_socket_addmembership_multicastaddress_multicastinterface" id="all_socket_addmembership_multicastaddress_multicastinterface">#</a></span></h3>
<div class="signature"><ul>
<li><code>multicastAddress</code> String</li>
<li><code>multicastInterface</code> String, Optional</li>
</div></ul>
<p>Tells the kernel to join a multicast group with <code>IP_ADD_MEMBERSHIP</code> socket option.
</p>
<p>If <code>multicastInterface</code> is not specified, the OS will try to add membership to all valid
interfaces.
</p>
<h3>socket.dropMembership(multicastAddress, [multicastInterface])<span><a class="mark" href="#all_socket_dropmembership_multicastaddress_multicastinterface" id="all_socket_dropmembership_multicastaddress_multicastinterface">#</a></span></h3>
<div class="signature"><ul>
<li><code>multicastAddress</code> String</li>
<li><code>multicastInterface</code> String, Optional</li>
</div></ul>
<p>Opposite of <code>addMembership</code> - tells the kernel to leave a multicast group with
<code>IP_DROP_MEMBERSHIP</code> socket option. This is automatically called by the kernel
when the socket is closed or process terminates, so most apps will never need to call
this.
</p>
<p>If <code>multicastInterface</code> is not specified, the OS will try to drop membership to all valid
interfaces.
</p>
<h3>socket.unref()<span><a class="mark" href="#all_socket_unref_1" id="all_socket_unref_1">#</a></span></h3>
<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>
<h3>socket.ref()<span><a class="mark" href="#all_socket_ref_1" id="all_socket_ref_1">#</a></span></h3>
<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>
<h1>DNS<span><a class="mark" href="#all_dns" id="all_dns">#</a></span></h1>
<pre class="api_stability_3">Stability: 3 - Stable</pre><p>Use <code>require('dns')</code> to access this module. All methods in the dns module
use C-Ares except for <code>dns.lookup</code> which uses <code>getaddrinfo(3)</code> in a thread
pool. C-Ares is much faster than <code>getaddrinfo</code> but the system resolver is
more consistent with how other programs operate. When a user does
<code>net.connect(80, 'google.com')</code> or <code>http.get({ host: 'google.com' })</code> the
<code>dns.lookup</code> method is used. Users who need to do a large number of lookups
quickly should use the methods that go through C-Ares.
</p>
<p>Here is an example which resolves <code>'www.google.com'</code> then reverse
resolves the IP addresses which are returned.
</p>
<pre><code>var dns = require('dns');
dns.resolve4('www.google.com', function (err, addresses) {
if (err) throw err;
console.log('addresses: ' + JSON.stringify(addresses));
addresses.forEach(function (a) {
dns.reverse(a, function (err, domains) {
if (err) {
throw err;
}
console.log('reverse for ' + a + ': ' + JSON.stringify(domains));
});
});
});</code></pre>
<h2>dns.lookup(domain, [family], callback)<span><a class="mark" href="#all_dns_lookup_domain_family_callback" id="all_dns_lookup_domain_family_callback">#</a></span></h2>
<p>Resolves a domain (e.g. <code>'google.com'</code>) into the first found A (IPv4) or
AAAA (IPv6) record.
The <code>family</code> can be the integer <code>4</code> or <code>6</code>. Defaults to <code>null</code> that indicates
both Ip v4 and v6 address family.
</p>
<p>The callback has arguments <code>(err, address, family)</code>. The <code>address</code> argument
is a string representation of a IP v4 or v6 address. The <code>family</code> argument
is either the integer 4 or 6 and denotes the family of <code>address</code> (not
necessarily the value initially passed to <code>lookup</code>).
</p>
<p>On error, <code>err</code> is an <code>Error</code> 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 domain does not exist but also when the lookup fails in other ways
such as no available file descriptors.
</p>
<h2>dns.resolve(domain, [rrtype], callback)<span><a class="mark" href="#all_dns_resolve_domain_rrtype_callback" id="all_dns_resolve_domain_rrtype_callback">#</a></span></h2>
<p>Resolves a domain (e.g. <code>'google.com'</code>) into an array of the record types
specified by rrtype. Valid rrtypes are <code>'A'</code> (IPV4 addresses, default),
<code>'AAAA'</code> (IPV6 addresses), <code>'MX'</code> (mail exchange records), <code>'TXT'</code> (text
records), <code>'SRV'</code> (SRV records), <code>'PTR'</code> (used for reverse IP lookups),
<code>'NS'</code> (name server records) and <code>'CNAME'</code> (canonical name records).
</p>
<p>The callback has arguments <code>(err, addresses)</code>. 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 below.
</p>
<p>On error, <code>err</code> is an <code>Error</code> object, where <code>err.code</code> is
one of the error codes listed below.
</p>
<h2>dns.resolve4(domain, callback)<span><a class="mark" href="#all_dns_resolve4_domain_callback" id="all_dns_resolve4_domain_callback">#</a></span></h2>
<p>The same as <code>dns.resolve()</code>, but only for IPv4 queries (<code>A</code> records).
<code>addresses</code> is 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(domain, callback)<span><a class="mark" href="#all_dns_resolve6_domain_callback" id="all_dns_resolve6_domain_callback">#</a></span></h2>
<p>The same as <code>dns.resolve4()</code> except for IPv6 queries (an <code>AAAA</code> query).
</p>
<h2>dns.resolveMx(domain, callback)<span><a class="mark" href="#all_dns_resolvemx_domain_callback" id="all_dns_resolvemx_domain_callback">#</a></span></h2>
<p>The same as <code>dns.resolve()</code>, but only for mail exchange queries (<code>MX</code> records).
</p>
<p><code>addresses</code> is an array of MX records, each with a priority and an exchange
attribute (e.g. <code>[{'priority': 10, 'exchange': 'mx.example.com'},...]</code>).
</p>
<h2>dns.resolveTxt(domain, callback)<span><a class="mark" href="#all_dns_resolvetxt_domain_callback" id="all_dns_resolvetxt_domain_callback">#</a></span></h2>
<p>The same as <code>dns.resolve()</code>, but only for text queries (<code>TXT</code> records).
<code>addresses</code> is an array of the text records available for <code>domain</code> (e.g.,
<code>['v=spf1 ip4:0.0.0.0 ~all']</code>).
</p>
<h2>dns.resolveSrv(domain, callback)<span><a class="mark" href="#all_dns_resolvesrv_domain_callback" id="all_dns_resolvesrv_domain_callback">#</a></span></h2>
<p>The same as <code>dns.resolve()</code>, but only for service records (<code>SRV</code> records).
<code>addresses</code> is an array of the SRV records available for <code>domain</code>. Properties
of SRV records are priority, weight, port, and name (e.g.,
<code>[{'priority': 10, {'weight': 5, 'port': 21223, 'name': 'service.example.com'}, ...]</code>).
</p>
<h2>dns.resolveNs(domain, callback)<span><a class="mark" href="#all_dns_resolvens_domain_callback" id="all_dns_resolvens_domain_callback">#</a></span></h2>
<p>The same as <code>dns.resolve()</code>, but only for name server records (<code>NS</code> records).
<code>addresses</code> is an array of the name server records available for <code>domain</code>
(e.g., <code>['ns1.example.com', 'ns2.example.com']</code>).
</p>
<h2>dns.resolveCname(domain, callback)<span><a class="mark" href="#all_dns_resolvecname_domain_callback" id="all_dns_resolvecname_domain_callback">#</a></span></h2>
<p>The same as <code>dns.resolve()</code>, but only for canonical name records (<code>CNAME</code>
records). <code>addresses</code> is an array of the canonical name records available for
<code>domain</code> (e.g., <code>['bar.example.com']</code>).
</p>
<h2>dns.reverse(ip, callback)<span><a class="mark" href="#all_dns_reverse_ip_callback" id="all_dns_reverse_ip_callback">#</a></span></h2>
<p>Reverse resolves an ip address to an array of domain names.
</p>
<p>The callback has arguments <code>(err, domains)</code>.
</p>
<p>On error, <code>err</code> is an <code>Error</code> object, where <code>err.code</code> is
one of the error codes listed below.
</p>
<h2>Error codes<span><a class="mark" href="#all_error_codes" id="all_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 domain name.</li>
<li><code>dns.BADFAMILY</code>: Unsupported address family.</li>
<li><code>dns.BADRESP</code>: Misformatted DNS reply.</li>
<li><code>dns.CONNREFUSED</code>: Could not contact DNS servers.</li>
<li><code>dns.TIMEOUT</code>: Timeout while contacting DNS servers.</li>
<li><code>dns.EOF</code>: End of file.</li>
<li><code>dns.FILE</code>: Error reading file.</li>
<li><code>dns.NOMEM</code>: Out of memory.</li>
<li><code>dns.DESTRUCTION</code>: Channel is being destroyed.</li>
<li><code>dns.BADSTR</code>: Misformatted string.</li>
<li><code>dns.BADFLAGS</code>: Illegal flags specified.</li>
<li><code>dns.NONAME</code>: Given 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>
<h1>HTTP<span><a class="mark" href="#all_http" id="all_http">#</a></span></h1>
<pre class="api_stability_3">Stability: 3 - Stable</pre><p>To use the HTTP server and client one must <code>require('http')</code>.
</p>
<p>The HTTP interfaces in Node 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',
'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'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>
<h2>http.STATUS_CODES<span><a class="mark" href="#all_http_status_codes" id="all_http_status_codes">#</a></span></h2>
<div class="signature"><ul>
<li><span class="type">Object</span></li>
</div></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.createServer([requestListener])<span><a class="mark" href="#all_http_createserver_requestlistener" id="all_http_createserver_requestlistener">#</a></span></h2>
<p>Returns a new web server object.
</p>
<p>The <code>requestListener</code> is a function which is automatically
added to the <code>'request'</code> event.
</p>
<h2>http.createClient([port], [host])<span><a class="mark" href="#all_http_createclient_port_host" id="all_http_createclient_port_host">#</a></span></h2>
<p>This function is <strong>deprecated</strong>; please use <a href="http.html#http_http_request_options_callback">http.request()</a> instead.
Constructs a new HTTP client. <code>port</code> and <code>host</code> refer to the server to be
connected to.
</p>
<h2>Class: http.Server<span><a class="mark" href="#all_class_http_server" id="all_class_http_server">#</a></span></h2>
<p>This is an <a href="events.html#events_class_events_eventemitter">EventEmitter</a> with the following events:
</p>
<h3>Event: 'request'<span><a class="mark" href="#all_event_request" id="all_event_request">#</a></span></h3>
<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_http_incomingmessage">http.IncomingMessage</a> and <code>response</code> is
an instance of <a href="#http_class_http_serverresponse">http.ServerResponse</a>.
</p>
<h3>Event: 'connection'<span><a class="mark" href="#all_event_connection_1" id="all_event_connection_1">#</a></span></h3>
<p><code>function (socket) { }</code>
</p>
<p> When a new TCP stream is established. <code>socket</code> is an object of type
<code>net.Socket</code>. 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: 'close'<span><a class="mark" href="#all_event_close_4" id="all_event_close_4">#</a></span></h3>
<p><code>function () { }</code>
</p>
<p> Emitted when the server closes.
</p>
<h3>Event: 'checkContinue'<span><a class="mark" href="#all_event_checkcontinue" id="all_event_checkcontinue">#</a></span></h3>
<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">response.writeContinue()</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: 'connect'<span><a class="mark" href="#all_event_connect_1" id="all_event_connect_1">#</a></span></h3>
<p><code>function (request, socket, head) { }</code>
</p>
<p>Emitted each time a client requests a http CONNECT method. If this event isn't
listened for, then clients requesting a CONNECT 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: 'upgrade'<span><a class="mark" href="#all_event_upgrade" id="all_event_upgrade">#</a></span></h3>
<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>Event: 'clientError'<span><a class="mark" href="#all_event_clienterror_1" id="all_event_clienterror_1">#</a></span></h3>
<p><code>function (exception, socket) { }</code>
</p>
<p>If a client connection emits an 'error' event - it will forwarded here.
</p>
<p><code>socket</code> is the <code>net.Socket</code> object that the error originated from.
</p>
<h3>server.listen(port, [hostname], [backlog], [callback])<span><a class="mark" href="#all_server_listen_port_hostname_backlog_callback" id="all_server_listen_port_hostname_backlog_callback">#</a></span></h3>
<p>Begin accepting connections on the specified port and hostname. If the
hostname is omitted, the server will accept connections directed to any
IPv4 address (<code>INADDR_ANY</code>).
</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. The last parameter <code>callback</code> will be added as
a listener for the <a href="net.html#net_event_listening">'listening'</a> event. See also <a href="net.html#net_server_listen_port_host_backlog_callback">net.Server.listen(port)</a>.
</p>
<h3>server.listen(path, [callback])<span><a class="mark" href="#all_server_listen_path_callback_1" id="all_server_listen_path_callback_1">#</a></span></h3>
<p>Start a UNIX socket server listening for connections on the given <code>path</code>.
</p>
<p>This function is asynchronous. The last parameter <code>callback</code> will be added as
a listener for the <a href="net.html#net_event_listening">'listening'</a> event. See also <a href="net.html#net_server_listen_path_callback">net.Server.listen(path)</a>.
</p>
<h3>server.listen(handle, [callback])<span><a class="mark" href="#all_server_listen_handle_callback_1" id="all_server_listen_handle_callback_1">#</a></span></h3>
<div class="signature"><ul>
<li><code>handle</code> <span class="type">Object</span></li>
<li><code>callback</code> <span class="type">Function</span></li>
</div></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. The last parameter <code>callback</code> will be added as
a listener for the <a href="net.html#event_listening_">'listening'</a> event.
See also <a href="net.html#net_server_listen_handle_callback">net.Server.listen()</a>.
</p>
<h3>server.close([callback])<span><a class="mark" href="#all_server_close_callback_1" id="all_server_close_callback_1">#</a></span></h3>
<p>Stops the server from accepting new connections. See <a href="net.html#net_server_close_callback">net.Server.close()</a>.
</p>
<h3>server.maxHeadersCount<span><a class="mark" href="#all_server_maxheaderscount" id="all_server_maxheaderscount">#</a></span></h3>
<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="#all_server_settimeout_msecs_callback" id="all_server_settimeout_msecs_callback">#</a></span></h3>
<div class="signature"><ul>
<li><code>msecs</code> <span class="type">Number</span></li>
<li><code>callback</code> <span class="type">Function</span></li>
</div></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>
<h3>server.timeout<span><a class="mark" href="#all_server_timeout" id="all_server_timeout">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">Number</span> Default = 120000 (2 minutes)</li>
</div></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="#all_class_http_serverresponse" id="all_class_http_serverresponse">#</a></span></h2>
<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 the <a href="stream.html#stream_class_stream_writable">Writable Stream</a> interface. This is an
<a href="events.html#events_class_events_eventemitter">EventEmitter</a> with the following events:
</p>
<h3>Event: 'close'<span><a class="mark" href="#all_event_close_5" id="all_event_close_5">#</a></span></h3>
<p><code>function () { }</code>
</p>
<p>Indicates that the underlying connection was terminated before
<a href="#http_response_end_data_encoding">response.end()</a> was called or able to flush.
</p>
<h3>Event: 'finish'<span><a class="mark" href="#all_event_finish_1" id="all_event_finish_1">#</a></span></h3>
<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.writeContinue()<span><a class="mark" href="#all_response_writecontinue" id="all_response_writecontinue">#</a></span></h3>
<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">'checkContinue'</a> event on <code>Server</code>.
</p>
<h3>response.writeHead(statusCode, [reasonPhrase], [headers])<span><a class="mark" href="#all_response_writehead_statuscode_reasonphrase_headers" id="all_response_writehead_statuscode_reasonphrase_headers">#</a></span></h3>
<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>reasonPhrase</code> as the second
argument.
</p>
<p>Example:
</p>
<pre><code>var body = 'hello world';
response.writeHead(200, {
'Content-Length': body.length,
'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">response.end()</a> is called.
</p>
<p>If you call <a href="#http_response_write_chunk_encoding">response.write()</a> or <a href="#http_response_end_data_encoding">response.end()</a> before calling this, the
implicit/mutable headers will be calculated and call this function for you.
</p>
<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 does not check whether Content-Length and the length of the body
which has been transmitted are equal or not.
</p>
<h3>response.setTimeout(msecs, callback)<span><a class="mark" href="#all_response_settimeout_msecs_callback" id="all_response_settimeout_msecs_callback">#</a></span></h3>
<div class="signature"><ul>
<li><code>msecs</code> <span class="type">Number</span></li>
<li><code>callback</code> <span class="type">Function</span></li>
</div></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>
<h3>response.statusCode<span><a class="mark" href="#all_response_statuscode" id="all_response_statuscode">#</a></span></h3>
<p>When using implicit headers (not calling <a href="#http_response_writehead_statuscode_reasonphrase_headers">response.writeHead()</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>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.setHeader(name, value)<span><a class="mark" href="#all_response_setheader_name_value" id="all_response_setheader_name_value">#</a></span></h3>
<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>response.setHeader("Content-Type", "text/html");</code></pre>
<p>or
</p>
<pre><code>response.setHeader("Set-Cookie", ["type=ninja", "language=javascript"]);</code></pre>
<h3>response.headersSent<span><a class="mark" href="#all_response_headerssent" id="all_response_headerssent">#</a></span></h3>
<p>Boolean (read-only). True if headers were sent, false otherwise.
</p>
<h3>response.sendDate<span><a class="mark" href="#all_response_senddate" id="all_response_senddate">#</a></span></h3>
<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.getHeader(name)<span><a class="mark" href="#all_response_getheader_name" id="all_response_getheader_name">#</a></span></h3>
<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>var contentType = response.getHeader('content-type');</code></pre>
<h3>response.removeHeader(name)<span><a class="mark" href="#all_response_removeheader_name" id="all_response_removeheader_name">#</a></span></h3>
<p>Removes a header that's queued for implicit sending.
</p>
<p>Example:
</p>
<pre><code>response.removeHeader("Content-Encoding");</code></pre>
<h3>response.write(chunk, [encoding])<span><a class="mark" href="#all_response_write_chunk_encoding" id="all_response_write_chunk_encoding">#</a></span></h3>
<p>If this method is called and <a href="#http_response_writehead_statuscode_reasonphrase_headers">response.writeHead()</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>.
</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 <code>response.write()</code> is called, it will send the buffered
header information and the first body to the client. The second time
<code>response.write()</code> is called, Node 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 again free.
</p>
<h3>response.addTrailers(headers)<span><a class="mark" href="#all_response_addtrailers_headers" id="all_response_addtrailers_headers">#</a></span></h3>
<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>response.writeHead(200, { 'Content-Type': 'text/plain',
'Trailer': 'Content-MD5' });
response.write(fileData);
response.addTrailers({'Content-MD5': "7895bf4b8828b55ceaf47747b4bca667"});
response.end();</code></pre>
<h3>response.end([data], [encoding])<span><a class="mark" href="#all_response_end_data_encoding" id="all_response_end_data_encoding">#</a></span></h3>
<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 <code>response.write(data, encoding)</code>
followed by <code>response.end()</code>.
</p>
<h2>http.request(options, [callback])<span><a class="mark" href="#all_http_request_options_callback" id="all_http_request_options_callback">#</a></span></h2>
<p>Node 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">url.parse()</a>.
</p>
<p>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>: To support <code>url.parse()</code> <code>hostname</code> is preferred over <code>host</code></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></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">Agent</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">global Agent</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 <a href="#http_event_response">'response'</a> event.
</p>
<p><code>http.request()</code> returns an instance of the <a href="#http_class_http_clientrequest">http.ClientRequest</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>var options = {
hostname: 'www.google.com',
port: 80,
path: '/upload',
method: 'POST'
};
var req = http.request(options, function(res) {
console.log('STATUS: ' + res.statusCode);
console.log('HEADERS: ' + JSON.stringify(res.headers));
res.setEncoding('utf8');
res.on('data', function (chunk) {
console.log('BODY: ' + chunk);
});
});
req.on('error', function(e) {
console.log('problem with request: ' + e.message);
});
// write data to request body
req.write('data\n');
req.write('data\n');
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.
</p>
<p>There are a few special headers that should be noted.
</p>
<ul>
<li><p>Sending a 'Connection: keep-alive' will notify Node 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>
<h2>http.get(options, [callback])<span><a class="mark" href="#all_http_get_options_callback" id="all_http_get_options_callback">#</a></span></h2>
<p>Since most requests are GET requests without bodies, Node provides this
convenience method. The only difference between this method and <code>http.request()</code>
is that it sets the method to GET and calls <code>req.end()</code> automatically.
</p>
<p>Example:
</p>
<pre><code>http.get("http://www.google.com/index.html", function(res) {
console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
console.log("Got error: " + e.message);
});</code></pre>
<h2>Class: http.Agent<span><a class="mark" href="#all_class_http_agent" id="all_class_http_agent">#</a></span></h2>
<p>In node 0.5.3+ there is a new implementation of the HTTP Agent which is used
for pooling sockets used in HTTP client requests.
</p>
<p>Previously, a single agent instance helped pool for a single host+port. The
current implementation now holds sockets for any number of hosts.
</p>
<p>The current 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's pool has the
benefit of keep-alive when under load but still does not require developers
to manually close the HTTP clients using keep-alive.
</p>
<p>Sockets are removed from the agent's pool when the socket emits either a
"close" event or a special "agentRemove" 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>http.get(options, function(res) {
// Do stuff
}).on("socket", function (socket) {
socket.emit("agentRemove");
});</code></pre>
<p>Alternatively, you could just opt out of pooling entirely using <code>agent:false</code>:
</p>
<pre><code>http.get({hostname:'localhost', port:80, path:'/', agent:false}, function (res) {
// Do stuff
})</code></pre>
<h3>agent.maxSockets<span><a class="mark" href="#all_agent_maxsockets" id="all_agent_maxsockets">#</a></span></h3>
<p>By default set to 5. 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.sockets<span><a class="mark" href="#all_agent_sockets" id="all_agent_sockets">#</a></span></h3>
<p>An object which contains arrays of sockets currently in use by the Agent. Do not
modify.
</p>
<h3>agent.requests<span><a class="mark" href="#all_agent_requests" id="all_agent_requests">#</a></span></h3>
<p>An object which contains queues of requests that have not yet been assigned to
sockets. Do not modify.
</p>
<h2>http.globalAgent<span><a class="mark" href="#all_http_globalagent" id="all_http_globalagent">#</a></span></h2>
<p>Global instance of Agent which is used as the default for all http client
requests.
</p>
<h2>Class: http.ClientRequest<span><a class="mark" href="#all_class_http_clientrequest" id="all_class_http_clientrequest">#</a></span></h2>
<p>This object is created internally and returned from <code>http.request()</code>. 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_http_incomingmessage">http.IncomingMessage</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 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_events_eventemitter">EventEmitter</a> with the following events:
</p>
<h3>Event 'response'<span><a class="mark" href="#all_event_response" id="all_event_response">#</a></span></h3>
<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_http_incomingmessage">http.IncomingMessage</a>.
</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>socketPath</code>: Unix Domain Socket (use one of host:port or socketPath)</li>
</ul>
<h3>Event: 'socket'<span><a class="mark" href="#all_event_socket" id="all_event_socket">#</a></span></h3>
<p><code>function (socket) { }</code>
</p>
<p>Emitted after a socket is assigned to this request.
</p>
<h3>Event: 'connect'<span><a class="mark" href="#all_event_connect_2" id="all_event_connect_2">#</a></span></h3>
<p><code>function (response, socket, head) { }</code>
</p>
<p>Emitted each time a server responds to a request with a CONNECT method. If this
event isn't being listened for, clients receiving a CONNECT method will have
their connections closed.
</p>
<p>A client server pair that show you how to listen for the <code>connect</code> event.
</p>
<pre><code>var http = require('http');
var net = require('net');
var url = require('url');
// Create an HTTP tunneling proxy
var proxy = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('okay');
});
proxy.on('connect', function(req, cltSocket, head) {
// connect to an origin server
var srvUrl = url.parse('http://' + req.url);
var srvSocket = net.connect(srvUrl.port, srvUrl.hostname, function() {
cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
'Proxy-agent: Node-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', function() {
// 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', function(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', function(chunk) {
console.log(chunk.toString());
});
socket.on('end', function() {
proxy.close();
});
});
});</code></pre>
<h3>Event: 'upgrade'<span><a class="mark" href="#all_event_upgrade_1" id="all_event_upgrade_1">#</a></span></h3>
<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>var http = require('http');
// Create an HTTP server
var srv = http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('okay');
});
srv.on('upgrade', function(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', function() {
// 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', function(res, socket, upgradeHead) {
console.log('got upgraded!');
socket.end();
process.exit(0);
});
});</code></pre>
<h3>Event: 'continue'<span><a class="mark" href="#all_event_continue" id="all_event_continue">#</a></span></h3>
<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>request.write(chunk, [encoding])<span><a class="mark" href="#all_request_write_chunk_encoding" id="all_request_write_chunk_encoding">#</a></span></h3>
<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">Buffer</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>
<h3>request.end([data], [encoding])<span><a class="mark" href="#all_request_end_data_encoding" id="all_request_end_data_encoding">#</a></span></h3>
<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
<code>request.write(data, encoding)</code> followed by <code>request.end()</code>.
</p>
<h3>request.abort()<span><a class="mark" href="#all_request_abort" id="all_request_abort">#</a></span></h3>
<p>Aborts a request. (New since v0.3.8.)
</p>
<h3>request.setTimeout(timeout, [callback])<span><a class="mark" href="#all_request_settimeout_timeout_callback" id="all_request_settimeout_timeout_callback">#</a></span></h3>
<p>Once a socket is assigned to this request and is connected
<a href="net.html#net_socket_settimeout_timeout_callback">socket.setTimeout()</a> will be called.
</p>
<h3>request.setNoDelay([noDelay])<span><a class="mark" href="#all_request_setnodelay_nodelay" id="all_request_setnodelay_nodelay">#</a></span></h3>
<p>Once a socket is assigned to this request and is connected
<a href="net.html#net_socket_setnodelay_nodelay">socket.setNoDelay()</a> will be called.
</p>
<h3>request.setSocketKeepAlive([enable], [initialDelay])<span><a class="mark" href="#all_request_setsocketkeepalive_enable_initialdelay" id="all_request_setsocketkeepalive_enable_initialdelay">#</a></span></h3>
<p>Once a socket is assigned to this request and is connected
<a href="net.html#net_socket_setkeepalive_enable_initialdelay">socket.setKeepAlive()</a> will be called.
</p>
<h2>http.IncomingMessage<span><a class="mark" href="#all_http_incomingmessage" id="all_http_incomingmessage">#</a></span></h2>
<p>An <code>IncomingMessage</code> object is created by <a href="#http_class_http_server">http.Server</a> or
<a href="#http_class_http_clientrequest">http.ClientRequest</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: 'close'<span><a class="mark" href="#all_event_close_6" id="all_event_close_6">#</a></span></h3>
<p><code>function () { }</code>
</p>
<p>Indicates that the underlaying connection was closed.
Just like <code>'end'</code>, this event occurs only once per response.
</p>
<h3>message.httpVersion<span><a class="mark" href="#all_message_httpversion" id="all_message_httpversion">#</a></span></h3>
<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>response.httpVersionMajor</code> is the first integer and
<code>response.httpVersionMinor</code> is the second.
</p>
<h3>message.headers<span><a class="mark" href="#all_message_headers" id="all_message_headers">#</a></span></h3>
<p>The request/response headers object.
</p>
<p>Read only map of header names and values. Header names are lower-cased.
Example:
</p>
<pre><code>// Prints something like:
//
// { 'user-agent': 'curl/7.22.0',
// host: '127.0.0.1:8000',
// accept: '*/*' }
console.log(request.headers);</code></pre>
<h3>message.trailers<span><a class="mark" href="#all_message_trailers" id="all_message_trailers">#</a></span></h3>
<p>The request/response trailers object. Only populated after the 'end' event.
</p>
<h3>message.setTimeout(msecs, callback)<span><a class="mark" href="#all_message_settimeout_msecs_callback" id="all_message_settimeout_msecs_callback">#</a></span></h3>
<div class="signature"><ul>
<li><code>msecs</code> <span class="type">Number</span></li>
<li><code>callback</code> <span class="type">Function</span></li>
</div></ul>
<p>Calls <code>message.connection.setTimeout(msecs, callback)</code>.
</p>
<h3>message.method<span><a class="mark" href="#all_message_method" id="all_message_method">#</a></span></h3>
<p><strong>Only valid for request obtained from <a href="#http_class_http_server">http.Server</a>.</strong>
</p>
<p>The request method as a string. Read only. Example:
<code>'GET'</code>, <code>'DELETE'</code>.
</p>
<h3>message.url<span><a class="mark" href="#all_message_url" id="all_message_url">#</a></span></h3>
<p><strong>Only valid for request obtained from <a href="#http_class_http_server">http.Server</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 params 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>
<h3>message.statusCode<span><a class="mark" href="#all_message_statuscode" id="all_message_statuscode">#</a></span></h3>
<p><strong>Only valid for response obtained from <code>http.ClientRequest</code>.</strong>
</p>
<p>The 3-digit HTTP response status code. E.G. <code>404</code>.
</p>
<h3>message.socket<span><a class="mark" href="#all_message_socket" id="all_message_socket">#</a></span></h3>
<p>The <code>net.Socket</code> object associated with the connection.
</p>
<p>With HTTPS support, use request.connection.verifyPeer() and
request.connection.getPeerCertificate() to obtain the client's
authentication details.
</p>
<h1>HTTPS<span><a class="mark" href="#all_https" id="all_https">#</a></span></h1>
<pre class="api_stability_3">Stability: 3 - Stable</pre><p>HTTPS is the HTTP protocol over TLS/SSL. In Node this is implemented as a
separate module.
</p>
<h2>Class: https.Server<span><a class="mark" href="#all_class_https_server" id="all_class_https_server">#</a></span></h2>
<p>This class is a subclass of <code>tls.Server</code> and emits events same as
<code>http.Server</code>. See <code>http.Server</code> for more information.
</p>
<h2>https.createServer(options, [requestListener])<span><a class="mark" href="#all_https_createserver_options_requestlistener" id="all_https_createserver_options_requestlistener">#</a></span></h2>
<p>Returns a new HTTPS web server object. The <code>options</code> is similar to
<a href="tls.html#tls_tls_createserver_options_secureconnectionlistener">tls.createServer()</a>. The <code>requestListener</code> is a function which is
automatically added to the <code>'request'</code> event.
</p>
<p>Example:
</p>
<pre><code>// curl -k https://localhost:8000/
var https = require('https');
var fs = require('fs');
var options = {
key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);</code></pre>
<p>Or
</p>
<pre><code>var https = require('https');
var fs = require('fs');
var options = {
pfx: fs.readFileSync('server.pfx')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);</code></pre>
<h3>server.listen(port, [host], [backlog], [callback])<span><a class="mark" href="#all_server_listen_port_host_backlog_callback_1" id="all_server_listen_port_host_backlog_callback_1">#</a></span></h3>
<h3>server.listen(path, [callback])<span><a class="mark" href="#all_server_listen_path_callback_2" id="all_server_listen_path_callback_2">#</a></span></h3>
<h3>server.listen(handle, [callback])<span><a class="mark" href="#all_server_listen_handle_callback_2" id="all_server_listen_handle_callback_2">#</a></span></h3>
<p>See <a href="http.html#http_server_listen_port_hostname_backlog_callback">http.listen()</a> for details.
</p>
<h3>server.close([callback])<span><a class="mark" href="#all_server_close_callback_2" id="all_server_close_callback_2">#</a></span></h3>
<p>See <a href="http.html#http_server_close_callback">http.close()</a> for details.
</p>
<h2>https.request(options, callback)<span><a class="mark" href="#all_https_request_options_callback" id="all_https_request_options_callback">#</a></span></h2>
<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.parse">url.parse()</a>.
</p>
<p>All options from <a href="http.html#http_http_request_options_callback">http.request()</a> are valid.
</p>
<p>Example:
</p>
<pre><code>var https = require('https');
var options = {
hostname: 'encrypted.google.com',
port: 443,
path: '/',
method: 'GET'
};
var req = https.request(options, function(res) {
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);
res.on('data', function(d) {
process.stdout.write(d);
});
});
req.end();
req.on('error', function(e) {
console.error(e);
});</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>: To support <code>url.parse()</code> <code>hostname</code> is preferred over <code>host</code></li>
<li><code>port</code>: Port of remote server. Defaults to 443.</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></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">Agent</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">globalAgent</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.html#tls_tls_connect_options_callback">tls.connect()</a> can also be specified. However, a
<a href="#https_https_globalagent">globalAgent</a> silently ignores these.
</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>: An authority certificate or array of authority certificates to check
the remote host against.</li>
<li><code>ciphers</code>: A string describing the ciphers to use or exclude. Consult
<a href="http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT">http://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="http://www.openssl.org/docs/ssl/ssl.html#DEALING_WITH_PROTOCOL_METHODS">SSL_METHODS</a>.</li>
</ul>
<p>In order to specify these options, use a custom <code>Agent</code>.
</p>
<p>Example:
</p>
<pre><code>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, function(res) {
...
}</code></pre>
<p>Or does not use an <code>Agent</code>.
</p>
<p>Example:
</p>
<pre><code>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, function(res) {
...
}</code></pre>
<h2>https.get(options, callback)<span><a class="mark" href="#all_https_get_options_callback" id="all_https_get_options_callback">#</a></span></h2>
<p>Like <code>http.get()</code> 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.parse">url.parse()</a>.
</p>
<p>Example:
</p>
<pre><code>var https = require('https');
https.get('https://encrypted.google.com/', function(res) {
console.log("statusCode: ", res.statusCode);
console.log("headers: ", res.headers);
res.on('data', function(d) {
process.stdout.write(d);
});
}).on('error', function(e) {
console.error(e);
});</code></pre>
<h2>Class: https.Agent<span><a class="mark" href="#all_class_https_agent" id="all_class_https_agent">#</a></span></h2>
<p>An Agent object for HTTPS similar to <a href="http.html#http_class_http_agent">http.Agent</a>. See <a href="#https_https_request_options_callback">https.request()</a>
for more information.
</p>
<h2>https.globalAgent<span><a class="mark" href="#all_https_globalagent" id="all_https_globalagent">#</a></span></h2>
<p>Global instance of <a href="#https_class_https_agent">https.Agent</a> for all HTTPS client requests.
</p>
<h1>URL<span><a class="mark" href="#all_url" id="all_url">#</a></span></h1>
<pre class="api_stability_3">Stability: 3 - Stable</pre><p>This module has utilities for URL resolution and parsing.
Call <code>require('url')</code> to use it.
</p>
<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.</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>.</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>
<p>The following methods are provided by the URL module:
</p>
<h2>url.parse(urlStr, [parseQueryString], [slashesDenoteHost])<span><a class="mark" href="#all_url_parse_urlstr_parsequerystring_slashesdenotehost" id="all_url_parse_urlstr_parsequerystring_slashesdenotehost">#</a></span></h2>
<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.
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.format(urlObj)<span><a class="mark" href="#all_url_format_urlobj" id="all_url_format_urlobj">#</a></span></h2>
<p>Take a parsed URL object, and return a formatted URL string.
</p>
<ul>
<li><code>href</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).</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></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>search</code> will be used in place of <code>query</code></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> is treated the same with or without the leading <code>?</code> (question mark)</li>
<li><code>hash</code> is treated the same with or without the leading <code>#</code> (pound sign, anchor)</li>
</ul>
<h2>url.resolve(from, to)<span><a class="mark" href="#all_url_resolve_from_to" id="all_url_resolve_from_to">#</a></span></h2>
<p>Take a base URL, and a href URL, and resolve them as a browser would for
an anchor tag. Examples:
</p>
<pre><code>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>
<h1>Query String<span><a class="mark" href="#all_query_string" id="all_query_string">#</a></span></h1>
<pre class="api_stability_3">Stability: 3 - Stable</pre><!--name=querystring-->
<p>This module provides utilities for dealing with query strings.
It provides the following methods:
</p>
<h2>querystring.stringify(obj, [sep], [eq])<span><a class="mark" href="#all_querystring_stringify_obj_sep_eq" id="all_querystring_stringify_obj_sep_eq">#</a></span></h2>
<p>Serialize an object to a query string.
Optionally override the default separator (<code>'&'</code>) and assignment (<code>'='</code>)
characters.
</p>
<p>Example:
</p>
<pre><code>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'</code></pre>
<h2>querystring.parse(str, [sep], [eq], [options])<span><a class="mark" href="#all_querystring_parse_str_sep_eq_options" id="all_querystring_parse_str_sep_eq_options">#</a></span></h2>
<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>Example:
</p>
<pre><code>querystring.parse('foo=bar&baz=qux&baz=quux&corge')
// returns
{ foo: 'bar', baz: ['qux', 'quux'], corge: '' }</code></pre>
<h2>querystring.escape<span><a class="mark" href="#all_querystring_escape" id="all_querystring_escape">#</a></span></h2>
<p>The escape function used by <code>querystring.stringify</code>,
provided so that it could be overridden if necessary.
</p>
<h2>querystring.unescape<span><a class="mark" href="#all_querystring_unescape" id="all_querystring_unescape">#</a></span></h2>
<p>The unescape function used by <code>querystring.parse</code>,
provided so that it could be overridden if necessary.
</p>
<h1>punycode<span><a class="mark" href="#all_punycode" id="all_punycode">#</a></span></h1>
<pre class="api_stability_2">Stability: 2 - Unstable</pre><p><a href="http://mths.be/punycode">Punycode.js</a> is bundled with Node.js v0.6.2+. 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="#all_punycode_decode_string" id="all_punycode_decode_string">#</a></span></h2>
<p>Converts a Punycode string of ASCII code points to a string of Unicode code
points.
</p>
<pre><code>// decode domain name parts
punycode.decode('maana-pta'); // 'mañana'
punycode.decode('--dqo34k'); // '☃-⌘'</code></pre>
<h2>punycode.encode(string)<span><a class="mark" href="#all_punycode_encode_string" id="all_punycode_encode_string">#</a></span></h2>
<p>Converts a string of Unicode code points to a Punycode string of ASCII code
points.
</p>
<pre><code>// encode domain name parts
punycode.encode('mañana'); // 'maana-pta'
punycode.encode('☃-⌘'); // '--dqo34k'</code></pre>
<h2>punycode.toUnicode(domain)<span><a class="mark" href="#all_punycode_tounicode_domain" id="all_punycode_tounicode_domain">#</a></span></h2>
<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>// decode domain names
punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com'
punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com'</code></pre>
<h2>punycode.toASCII(domain)<span><a class="mark" href="#all_punycode_toascii_domain" id="all_punycode_toascii_domain">#</a></span></h2>
<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>// encode domain names
punycode.toASCII('mañana.com'); // 'xn--maana-pta.com'
punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com'</code></pre>
<h2>punycode.ucs2<span><a class="mark" href="#all_punycode_ucs2" id="all_punycode_ucs2">#</a></span></h2>
<h3>punycode.ucs2.decode(string)<span><a class="mark" href="#all_punycode_ucs2_decode_string" id="all_punycode_ucs2_decode_string">#</a></span></h3>
<p>Creates an array containing the decimal code points of each Unicode character
in the string. While <a href="http://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>punycode.ucs2.decode('abc'); // [97, 98, 99]
// 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="#all_punycode_ucs2_encode_codepoints" id="all_punycode_ucs2_encode_codepoints">#</a></span></h3>
<p>Creates a string based on an array of decimal code points.
</p>
<pre><code>punycode.ucs2.encode([97, 98, 99]); // 'abc'
punycode.ucs2.encode([0x1D306]); // '\uD834\uDF06'</code></pre>
<h2>punycode.version<span><a class="mark" href="#all_punycode_version" id="all_punycode_version">#</a></span></h2>
<p>A string representing the current Punycode.js version number.
</p>
<h1>Readline<span><a class="mark" href="#all_readline" id="all_readline">#</a></span></h1>
<pre class="api_stability_2">Stability: 2 - Unstable</pre><p>To use this module, do <code>require('readline')</code>. Readline allows reading of a
stream (such as <code>process.stdin</code>) on a line-by-line basis.
</p>
<p>Note that once you've invoked this module, your node program will not
terminate until you've closed the interface. Here's how to allow your
program to gracefully exit:
</p>
<pre><code>var readline = require('readline');
var rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
rl.question("What do you think of node.js? ", function(answer) {
// TODO: Log the answer in a database
console.log("Thank you for your valuable feedback:", answer);
rl.close();
});</code></pre>
<h2>readline.createInterface(options)<span><a class="mark" href="#all_readline_createinterface_options" id="all_readline_createinterface_options">#</a></span></h2>
<p>Creates a readline <code>Interface</code> instance. Accepts an "options" 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 (Required).</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>
</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>function completer(line) {
var completions = '.help .error .exit .quit .q'.split(' ')
var hits = completions.filter(function(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>function completer(linePartial, callback) {
callback(null, [['123'], linePartial]);
}</code></pre>
<p><code>createInterface</code> is commonly used with <code>process.stdin</code> and
<code>process.stdout</code> in order to accept user input:
</p>
<pre><code>var readline = require('readline');
var 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
(<code>process.stdout</code> does this automatically when it is a TTY).
</p>
<h2>Class: Interface<span><a class="mark" href="#all_class_interface" id="all_class_interface">#</a></span></h2>
<p>The class that represents a readline interface with an input and output
stream.
</p>
<h3>rl.setPrompt(prompt, length)<span><a class="mark" href="#all_rl_setprompt_prompt_length" id="all_rl_setprompt_prompt_length">#</a></span></h3>
<p>Sets the prompt, for example when you run <code>node</code> on the command line, you see
<code>> </code>, which is node's prompt.
</p>
<h3>rl.prompt([preserveCursor])<span><a class="mark" href="#all_rl_prompt_preservecursor" id="all_rl_prompt_preservecursor">#</a></span></h3>
<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>
<h3>rl.question(query, callback)<span><a class="mark" href="#all_rl_question_query_callback" id="all_rl_question_query_callback">#</a></span></h3>
<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>Example usage:
</p>
<pre><code>interface.question('What is your favorite food?', function(answer) {
console.log('Oh, so your favorite food is ' + answer);
});</code></pre>
<h3>rl.pause()<span><a class="mark" href="#all_rl_pause" id="all_rl_pause">#</a></span></h3>
<p>Pauses the readline <code>input</code> stream, allowing it to be resumed later if needed.
</p>
<h3>rl.resume()<span><a class="mark" href="#all_rl_resume" id="all_rl_resume">#</a></span></h3>
<p>Resumes the readline <code>input</code> stream.
</p>
<h3>rl.close()<span><a class="mark" href="#all_rl_close" id="all_rl_close">#</a></span></h3>
<p>Closes the <code>Interface</code> instance, relinquishing control on the <code>input</code> and
<code>output</code> streams. The "close" event will also be emitted.
</p>
<h3>rl.write(data, [key])<span><a class="mark" href="#all_rl_write_data_key" id="all_rl_write_data_key">#</a></span></h3>
<p>Writes <code>data</code> to <code>output</code> stream. <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>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="#all_events_1" id="all_events_1">#</a></span></h2>
<h3>Event: 'line'<span><a class="mark" href="#all_event_line" id="all_event_line">#</a></span></h3>
<p><code>function (line) {}</code>
</p>
<p>Emitted whenever the <code>input</code> stream receives a <code>\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>rl.on('line', function (cmd) {
console.log('You just typed: '+cmd);
});</code></pre>
<h3>Event: 'pause'<span><a class="mark" href="#all_event_pause" id="all_event_pause">#</a></span></h3>
<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>rl.on('pause', function() {
console.log('Readline paused.');
});</code></pre>
<h3>Event: 'resume'<span><a class="mark" href="#all_event_resume" id="all_event_resume">#</a></span></h3>
<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>rl.on('resume', function() {
console.log('Readline resumed.');
});</code></pre>
<h3>Event: 'close'<span><a class="mark" href="#all_event_close_7" id="all_event_close_7">#</a></span></h3>
<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 "end" 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: 'SIGINT'<span><a class="mark" href="#all_event_sigint" id="all_event_sigint">#</a></span></h3>
<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>rl.on('SIGINT', function() {
rl.question('Are you sure you want to exit?', function(answer) {
if (answer.match(/^y(es)?$/i)) rl.pause();
});
});</code></pre>
<h3>Event: 'SIGTSTP'<span><a class="mark" href="#all_event_sigtstp" id="all_event_sigtstp">#</a></span></h3>
<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>rl.on('SIGTSTP', function() {
// This will override SIGTSTP and prevent the program from going to the
// background.
console.log('Caught SIGTSTP.');
});</code></pre>
<h3>Event: 'SIGCONT'<span><a class="mark" href="#all_event_sigcont" id="all_event_sigcont">#</a></span></h3>
<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 <code>fg(1)</code>. 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>rl.on('SIGCONT', function() {
// `prompt` will automatically resume the stream
rl.prompt();
});</code></pre>
<h2>Example: Tiny CLI<span><a class="mark" href="#all_example_tiny_cli" id="all_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>var readline = require('readline'),
rl = readline.createInterface(process.stdin, process.stdout);
rl.setPrompt('OHAI> ');
rl.prompt();
rl.on('line', function(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', function() {
console.log('Have a great day!');
process.exit(0);
});</code></pre>
<h2>readline.cursorTo(stream, x, y)<span><a class="mark" href="#all_readline_cursorto_stream_x_y" id="all_readline_cursorto_stream_x_y">#</a></span></h2>
<p>Move cursor to the specified position in a given TTY stream.
</p>
<h2>readline.moveCursor(stream, dx, dy)<span><a class="mark" href="#all_readline_movecursor_stream_dx_dy" id="all_readline_movecursor_stream_dx_dy">#</a></span></h2>
<p>Move cursor relative to it's current position in a given TTY stream.
</p>
<h2>readline.clearLine(stream, dir)<span><a class="mark" href="#all_readline_clearline_stream_dir" id="all_readline_clearline_stream_dir">#</a></span></h2>
<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="#all_readline_clearscreendown_stream" id="all_readline_clearscreendown_stream">#</a></span></h2>
<p>Clears the screen from the current position of the cursor down.
</p>
<h1>REPL<span><a class="mark" href="#all_repl" id="all_repl">#</a></span></h1>
<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>mjr:~$ node
Type '.help' for options.
> a = [ 1, 2, 3];
[ 1, 2, 3 ]
> a.forEach(function (v) {
... console.log(v);
... });
1
2
3</code></pre>
<p>For advanced line-editors, start node 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>repl.start(options)<span><a class="mark" href="#all_repl_start_options" id="all_repl_start_options">#</a></span></h2>
<p>Returns and starts a <code>REPLServer</code> instance. 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>
</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>Multiple REPLs may be started against the same running instance of node. 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>var net = require("net"),
repl = require("repl");
connections = 0;
repl.start({
prompt: "node via stdin> ",
input: process.stdin,
output: process.stdout
});
net.createServer(function (socket) {
connections += 1;
repl.start({
prompt: "node via Unix socket> ",
input: socket,
output: socket
}).on('exit', function() {
socket.end();
})
}).listen("/tmp/node-repl-sock");
net.createServer(function (socket) {
connections += 1;
repl.start({
prompt: "node via TCP socket> ",
input: socket,
output: socket
}).on('exit', function() {
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 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 <code>curl(1)</code>,
see: <a href="https://gist.github.com/2053342">https://gist.github.com/2053342</a>
</p>
<h3>Event: 'exit'<span><a class="mark" href="#all_event_exit_1" id="all_event_exit_1">#</a></span></h3>
<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 SIGINT, or pressing Ctrl+D
to signal "end" on the <code>input</code> stream.
</p>
<p>Example of listening for <code>exit</code>:
</p>
<pre><code>r.on('exit', function () {
console.log('Got "exit" event from repl!');
process.exit();
});</code></pre>
<h2>REPL Features<span><a class="mark" href="#all_repl_features" id="all_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>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>// repl_test.js
var repl = require("repl"),
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>mjr:~$ 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<blockquote>
<p>.save ./file/to/save.js</p>
</blockquote>
</li>
<li><code>.load</code> - Load a file into the current REPL session.<blockquote>
<p>.load ./file/to/load.js</p>
</blockquote>
</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>
</ul>
<h1>Executing JavaScript<span><a class="mark" href="#all_executing_javascript" id="all_executing_javascript">#</a></span></h1>
<pre class="api_stability_2">Stability: 2 - Unstable. See Caveats, below.</pre><!--name=vm-->
<p>You can access this module with:
</p>
<pre><code>var vm = require('vm');</code></pre>
<p>JavaScript code can be compiled and run immediately or compiled, saved, and run later.
</p>
<h2>Caveats<span><a class="mark" href="#all_caveats_1" id="all_caveats_1">#</a></span></h2>
<p>The <code>vm</code> module has many known issues and edge cases. If you run into
issues or unexpected behavior, please consult <a href="https://github.com/joyent/node/issues?labels=vm&state=open">the open issues on
GitHub</a>.
Some of the biggest problems are described below.
</p>
<h3>Sandboxes<span><a class="mark" href="#all_sandboxes" id="all_sandboxes">#</a></span></h3>
<p>The <code>sandbox</code> argument to <code>vm.runInNewContext</code> and <code>vm.createContext</code>,
along with the <code>initSandbox</code> argument to <code>vm.createContext</code>, do not
behave as one might normally expect and their behavior varies
between different versions of Node.
</p>
<p>The key issue to be aware of is that V8 provides no way to directly
control the global object used within a context. As a result, while
properties of your <code>sandbox</code> object will be available in the context,
any properties from the <code>prototype</code>s of the <code>sandbox</code> may not be
available. Furthermore, the <code>this</code> expression within the global scope
of the context evaluates to the empty object (<code>{}</code>) instead of to
your sandbox.
</p>
<p>Your sandbox's properties are also not shared directly with the script.
Instead, the properties of the sandbox are copied into the context at
the beginning of execution, and then after execution, the properties
are copied back out in an attempt to propagate any changes.
</p>
<h3>Globals<span><a class="mark" href="#all_globals" id="all_globals">#</a></span></h3>
<p>Properties of the global object, like <code>Array</code> and <code>String</code>, have
different values inside of a context. This means that common
expressions like <code>[] instanceof Array</code> or
<code>Object.getPrototypeOf([]) === Array.prototype</code> may not produce
expected results when used inside of scripts evaluated via the <code>vm</code> module.
</p>
<p>Some of these problems have known workarounds listed in the issues for
<code>vm</code> on GitHub. for example, <code>Array.isArray</code> works around
the example problem with <code>Array</code>.
</p>
<h2>vm.runInThisContext(code, [filename])<span><a class="mark" href="#all_vm_runinthiscontext_code_filename" id="all_vm_runinthiscontext_code_filename">#</a></span></h2>
<p><code>vm.runInThisContext()</code> compiles <code>code</code>, runs it and returns the result. Running
code does not have access to local scope. <code>filename</code> is optional, it's used only
in stack traces.
</p>
<p>Example of using <code>vm.runInThisContext</code> and <code>eval</code> to run the same code:
</p>
<pre><code>var localVar = 123,
usingscript, evaled,
vm = require('vm');
usingscript = vm.runInThisContext('localVar = 1;',
'myfile.vm');
console.log('localVar: ' + localVar + ', usingscript: ' +
usingscript);
evaled = eval('localVar = 1;');
console.log('localVar: ' + localVar + ', evaled: ' +
evaled);
// localVar: 123, usingscript: 1
// localVar: 1, evaled: 1</code></pre>
<p><code>vm.runInThisContext</code> does not have access to the local scope, so <code>localVar</code> is unchanged.
<code>eval</code> does have access to the local scope, so <code>localVar</code> is changed.
</p>
<p>In case of syntax error in <code>code</code>, <code>vm.runInThisContext</code> emits the syntax error to stderr
and throws an exception.
</p>
<h2>vm.runInNewContext(code, [sandbox], [filename])<span><a class="mark" href="#all_vm_runinnewcontext_code_sandbox_filename" id="all_vm_runinnewcontext_code_sandbox_filename">#</a></span></h2>
<p><code>vm.runInNewContext</code> compiles <code>code</code>, then runs it in <code>sandbox</code> and returns the
result. Running code does not have access to local scope. The object <code>sandbox</code>
will be used as the global object for <code>code</code>.
<code>sandbox</code> and <code>filename</code> are optional, <code>filename</code> is only used in stack traces.
</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>var util = require('util'),
vm = require('vm'),
sandbox = {
animal: 'cat',
count: 2
};
vm.runInNewContext('count += 1; name = "kitty"', sandbox, 'myfile.vm');
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. To prevent accidental
global variable leakage, <code>vm.runInNewContext</code> is quite useful, but safely running untrusted code
requires a separate process.
</p>
<p>In case of syntax error in <code>code</code>, <code>vm.runInNewContext</code> emits the syntax error to stderr
and throws an exception.
</p>
<h2>vm.runInContext(code, context, [filename])<span><a class="mark" href="#all_vm_runincontext_code_context_filename" id="all_vm_runincontext_code_context_filename">#</a></span></h2>
<p><code>vm.runInContext</code> compiles <code>code</code>, then runs it in <code>context</code> and returns the
result. A (V8) context comprises a global object, together with a set of
built-in objects and functions. Running code does not have access to local scope
and the global object held within <code>context</code> will be used as the global object
for <code>code</code>.
<code>filename</code> is optional, it's used only in stack traces.
</p>
<p>Example: compile and execute code in a existing context.
</p>
<pre><code>var util = require('util'),
vm = require('vm'),
initSandbox = {
animal: 'cat',
count: 2
},
context = vm.createContext(initSandbox);
vm.runInContext('count += 1; name = "CATT"', context, 'myfile.vm');
console.log(util.inspect(context));
// { animal: 'cat', count: 3, name: 'CATT' }</code></pre>
<p>Note that <code>createContext</code> will perform a shallow clone of the supplied sandbox object in order to
initialize the global object of the freshly constructed context.
</p>
<p>Note that running untrusted code is a tricky business requiring great care. To prevent accidental
global variable leakage, <code>vm.runInContext</code> is quite useful, but safely running untrusted code
requires a separate process.
</p>
<p>In case of syntax error in <code>code</code>, <code>vm.runInContext</code> emits the syntax error to stderr
and throws an exception.
</p>
<h2>vm.createContext([initSandbox])<span><a class="mark" href="#all_vm_createcontext_initsandbox" id="all_vm_createcontext_initsandbox">#</a></span></h2>
<p><code>vm.createContext</code> creates a new context which is suitable for use as the 2nd argument of a subsequent
call to <code>vm.runInContext</code>. A (V8) context comprises a global object together with a set of
build-in objects and functions. The optional argument <code>initSandbox</code> will be shallow-copied
to seed the initial contents of the global object used by the context.
</p>
<h2>vm.createScript(code, [filename])<span><a class="mark" href="#all_vm_createscript_code_filename" id="all_vm_createscript_code_filename">#</a></span></h2>
<p><code>createScript</code> compiles <code>code</code> but does not run it. Instead, it returns a
<code>vm.Script</code> object representing 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. <code>filename</code> is
optional, it's only used in stack traces.
</p>
<p>In case of syntax error in <code>code</code>, <code>createScript</code> prints the syntax error to stderr
and throws an exception.
</p>
<h2>Class: Script<span><a class="mark" href="#all_class_script" id="all_class_script">#</a></span></h2>
<p>A class for running scripts. Returned by vm.createScript.
</p>
<h3>script.runInThisContext()<span><a class="mark" href="#all_script_runinthiscontext" id="all_script_runinthiscontext">#</a></span></h3>
<p>Similar to <code>vm.runInThisContext</code> but a method of a precompiled <code>Script</code> object.
<code>script.runInThisContext</code> runs the code of <code>script</code> and returns the result.
Running code does not have access to local scope, but does have access to the <code>global</code> object
(v8: in actual context).
</p>
<p>Example of using <code>script.runInThisContext</code> to compile code once and run it multiple times:
</p>
<pre><code>var vm = require('vm');
globalVar = 0;
var script = vm.createScript('globalVar += 1', 'myfile.vm');
for (var i = 0; i < 1000 ; i += 1) {
script.runInThisContext();
}
console.log(globalVar);
// 1000</code></pre>
<h3>script.runInNewContext([sandbox])<span><a class="mark" href="#all_script_runinnewcontext_sandbox" id="all_script_runinnewcontext_sandbox">#</a></span></h3>
<p>Similar to <code>vm.runInNewContext</code> a method of a precompiled <code>Script</code> object.
<code>script.runInNewContext</code> runs the code of <code>script</code> with <code>sandbox</code> as the global object and returns the result.
Running code does not have access to local scope. <code>sandbox</code> is optional.
</p>
<p>Example: compile code that increments a global variable and sets one, then execute this code multiple times.
These globals are contained in the sandbox.
</p>
<pre><code>var util = require('util'),
vm = require('vm'),
sandbox = {
animal: 'cat',
count: 2
};
var script = vm.createScript('count += 1; name = "kitty"', 'myfile.vm');
for (var i = 0; i < 10 ; i += 1) {
script.runInNewContext(sandbox);
}
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. To prevent accidental
global variable leakage, <code>script.runInNewContext</code> is quite useful, but safely running untrusted code
requires a separate process.
</p>
<h1>Child Process<span><a class="mark" href="#all_child_process" id="all_child_process">#</a></span></h1>
<pre class="api_stability_3">Stability: 3 - Stable</pre><p>Node provides a tri-directional <code>popen(3)</code> facility through the
<code>child_process</code> module.
</p>
<p>It is possible to stream data through a child's <code>stdin</code>, <code>stdout</code>, and
<code>stderr</code> in a fully non-blocking way. (Note that some programs use
line-buffered I/O internally. That doesn't affect node.js but it means
data you send to the child process is not immediately consumed.)
</p>
<p>To create a child process use <code>require('child_process').spawn()</code> or
<code>require('child_process').fork()</code>. The semantics of each are slightly
different, and explained below.
</p>
<h2>Class: ChildProcess<span><a class="mark" href="#all_class_childprocess" id="all_class_childprocess">#</a></span></h2>
<p><code>ChildProcess</code> is an <a href="events.html#events_class_events_eventemitter">EventEmitter</a>.
</p>
<p>Child processes always have three streams associated with them. <code>child.stdin</code>,
<code>child.stdout</code>, and <code>child.stderr</code>. These may be shared with the stdio
streams of the parent process, or they may be separate stream objects
which can be piped to and from.
</p>
<p>The ChildProcess class is not intended to be used directly. Use the
<code>spawn()</code> or <code>fork()</code> methods to create a Child Process instance.
</p>
<h3>Event: 'error'<span><a class="mark" href="#all_event_error_6" id="all_event_error_6">#</a></span></h3>
<div class="signature"><ul>
<li><code>err</code> <span class="type">Error Object</span> the error.</li>
</div></ul>
<p>Emitted when:
</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 for whatever reason.</li>
</ol>
<p>Note that the <code>exit</code>-event may or may not fire after an error has occured. If
you are listening on both events to fire a function, remember to guard against
calling your function twice.
</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"><code>ChildProcess#send()</code></a>.
</p>
<h3>Event: 'exit'<span><a class="mark" href="#all_event_exit_2" id="all_event_exit_2">#</a></span></h3>
<div class="signature"><ul>
<li><code>code</code> <span class="type">Number</span> the exit code, if it exited normally.</li>
<li><code>signal</code> <span class="type">String</span> the signal passed to kill the child process, if it
was killed by the parent.</li>
</div></ul>
<p>This event is emitted after the child process ends. If the process terminated
normally, <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>.
</p>
<p>Note that the child process stdio streams might still be open.
</p>
<p>Also, note that node establishes signal handlers for <code>'SIGINT'</code> and <code>'SIGTERM</code>',
so it will not terminate due to receipt of those signals, it will exit.
</p>
<p>See <code>waitpid(2)</code>.
</p>
<h3>Event: 'close'<span><a class="mark" href="#all_event_close_8" id="all_event_close_8">#</a></span></h3>
<div class="signature"><ul>
<li><code>code</code> <span class="type">Number</span> the exit code, if it exited normally.</li>
<li><code>signal</code> <span class="type">String</span> the signal passed to kill the child process, if it
was killed by the parent.</li>
</div></ul>
<p>This event is emitted when the stdio streams of a child process have all
terminated. This is distinct from 'exit', since multiple processes
might share the same stdio streams.
</p>
<h3>Event: 'disconnect'<span><a class="mark" href="#all_event_disconnect" id="all_event_disconnect">#</a></span></h3>
<p>This event is emitted after calling the <code>.disconnect()</code> method in the parent
or in the child. After disconnecting it is no longer possible to send messages,
and the <code>.connected</code> property is false.
</p>
<h3>Event: 'message'<span><a class="mark" href="#all_event_message_1" id="all_event_message_1">#</a></span></h3>
<div class="signature"><ul>
<li><code>message</code> <span class="type">Object</span> a parsed JSON object or primitive value</li>
<li><code>sendHandle</code> <span class="type">Handle object</span> a Socket or Server object</li>
</div></ul>
<p>Messages send by <code>.send(message, [sendHandle])</code> are obtained using the
<code>message</code> event.
</p>
<h3>child.stdin<span><a class="mark" href="#all_child_stdin" id="all_child_stdin">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">Stream object</span></li>
</div></ul>
<p>A <code>Writable Stream</code> that represents the child process's <code>stdin</code>.
Closing this stream via <code>end()</code> often causes the child process to terminate.
</p>
<p>If the child stdio streams are shared with the parent, then this will
not be set.
</p>
<h3>child.stdout<span><a class="mark" href="#all_child_stdout" id="all_child_stdout">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">Stream object</span></li>
</div></ul>
<p>A <code>Readable Stream</code> that represents the child process's <code>stdout</code>.
</p>
<p>If the child stdio streams are shared with the parent, then this will
not be set.
</p>
<h3>child.stderr<span><a class="mark" href="#all_child_stderr" id="all_child_stderr">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">Stream object</span></li>
</div></ul>
<p>A <code>Readable Stream</code> that represents the child process's <code>stderr</code>.
</p>
<p>If the child stdio streams are shared with the parent, then this will
not be set.
</p>
<h3>child.pid<span><a class="mark" href="#all_child_pid" id="all_child_pid">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">Integer</span></li>
</div></ul>
<p>The PID of the child process.
</p>
<p>Example:
</p>
<pre><code>var spawn = require('child_process').spawn,
grep = spawn('grep', ['ssh']);
console.log('Spawned child pid: ' + grep.pid);
grep.stdin.end();</code></pre>
<h3>child.connected<span><a class="mark" href="#all_child_connected" id="all_child_connected">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">Boolean</span> Set to false after `.disconnect' is called</li>
</div></ul>
<p>If <code>.connected</code> is false, it is no longer possible to send messages.
</p>
<h3>child.kill([signal])<span><a class="mark" href="#all_child_kill_signal" id="all_child_kill_signal">#</a></span></h3>
<div class="signature"><ul>
<li><code>signal</code> <span class="type">String</span></li>
</div></ul>
<p>Send a signal to the child process. If no argument is given, the process will
be sent <code>'SIGTERM'</code>. See <code>signal(7)</code> for a list of available signals.
</p>
<pre><code>var spawn = require('child_process').spawn,
grep = spawn('grep', ['ssh']);
grep.on('close', function (code, signal) {
console.log('child process terminated due to receipt of signal '+signal);
});
// send SIGHUP to process
grep.kill('SIGHUP');</code></pre>
<p>May emit an <code>'error'</code> event when 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: if the PID (the process ID) has been reassigned
to another process, the signal will be delivered to that process instead.
What happens next is anyone's guess.
</p>
<p>Note that while the function is called <code>kill</code>, the signal delivered to the
child process may not actually kill it. <code>kill</code> really just sends a signal
to a process.
</p>
<p>See <code>kill(2)</code>
</p>
<h3>child.send(message, [sendHandle])<span><a class="mark" href="#all_child_send_message_sendhandle" id="all_child_send_message_sendhandle">#</a></span></h3>
<div class="signature"><ul>
<li><code>message</code> <span class="type">Object</span></li>
<li><code>sendHandle</code> <span class="type">Handle object</span></li>
</div></ul>
<p>When using <code>child_process.fork()</code> you can write to the child using
<code>child.send(message, [sendHandle])</code> and messages are received by
a <code>'message'</code> event on the child.
</p>
<p>For example:
</p>
<pre><code>var cp = require('child_process');
var n = cp.fork(__dirname + '/sub.js');
n.on('message', function(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>process.on('message', function(m) {
console.log('CHILD got message:', m);
});
process.send({ foo: 'bar' });</code></pre>
<p>In the child the <code>process</code> object will have a <code>send()</code> method, and <code>process</code>
will emit objects each time it receives a message on its channel.
</p>
<p>Please note that the <code>send()</code> method on both the parent and child are
synchronous - sending large chunks of data is not advised (pipes can be used
instead, see
<a href="#child_process_child_process_spawn_command_args_options"><code>child_process.spawn</code></a>).
</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 will not be emitted in
the <code>message</code> event, since they are internal messages used by node core.
Messages containing the prefix are emitted in the <code>internalMessage</code> event, you
should by all means avoid using this feature, it is subject to change without notice.
</p>
<p>The <code>sendHandle</code> option to <code>child.send()</code> is for sending a TCP server or
socket object to another process. The child will receive the object as its
second argument to the <code>message</code> event.
</p>
<p>Emits an <code>'error'</code> event if the message cannot be sent, for example because
the child process has already exited.
</p>
<h4>Example: sending server object<span><a class="mark" href="#all_example_sending_server_object" id="all_example_sending_server_object">#</a></span></h4>
<p>Here is an example of sending a server:
</p>
<pre><code>var child = require('child_process').fork('child.js');
// Open up the server object and send the handle.
var server = require('net').createServer();
server.on('connection', function (socket) {
socket.end('handled by parent');
});
server.listen(1337, function() {
child.send('server', server);
});</code></pre>
<p>And the child would the receive the server object as:
</p>
<pre><code>process.on('message', function(m, server) {
if (m === 'server') {
server.on('connection', function (socket) {
socket.end('handled by child');
});
}
});</code></pre>
<p>Note that the server is now shared between the parent and child, this means
that some connections will be handled by the parent and some by the child.
</p>
<p>For <code>dgram</code> servers the workflow is exactly the same. Here you listen on
a <code>message</code> event instead of <code>connection</code> and use <code>server.bind</code> instead of
<code>server.listen</code>. (Currently only supported on UNIX platforms.)
</p>
<h4>Example: sending socket object<span><a class="mark" href="#all_example_sending_socket_object" id="all_example_sending_socket_object">#</a></span></h4>
<p>Here is an example of sending a socket. It will spawn two children and handle
connections with the remote address <code>74.125.127.100</code> as VIP by sending the
socket to a "special" child process. Other sockets will go to a "normal" process.
</p>
<pre><code>var normal = require('child_process').fork('child.js', ['normal']);
var special = require('child_process').fork('child.js', ['special']);
// Open up the server and send sockets to child
var server = require('net').createServer();
server.on('connection', function (socket) {
// if this is a VIP
if (socket.remoteAddress === '74.125.127.100') {
special.send('socket', socket);
return;
}
// just the usual dudes
normal.send('socket', socket);
});
server.listen(1337);</code></pre>
<p>The <code>child.js</code> could look like this:
</p>
<pre><code>process.on('message', function(m, socket) {
if (m === 'socket') {
socket.end('You were handled as a ' + process.argv[2] + ' person');
}
});</code></pre>
<p>Note that once a single socket has been sent to a child the parent can no
longer keep track of when the socket is destroyed. To indicate this condition
the <code>.connections</code> property becomes <code>null</code>.
It is also recommended not to use <code>.maxConnections</code> in this condition.
</p>
<h3>child.disconnect()<span><a class="mark" href="#all_child_disconnect" id="all_child_disconnect">#</a></span></h3>
<p>Close 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>.connected</code> flag will be set to <code>false</code> in both the parent and
child, and it is no longer possible to send messages.
</p>
<p>The 'disconnect' event will be emitted when there are no messages in the process
of being received, most likely immediately.
</p>
<p>Note that you can also call <code>process.disconnect()</code> in the child process when the
child process has any open IPC channels with the parent (i.e <code>fork()</code>).
</p>
<h2>child_process.spawn(command, [args], [options])<span><a class="mark" href="#all_child_process_spawn_command_args_options" id="all_child_process_spawn_command_args_options">#</a></span></h2>
<div class="signature"><ul>
<li><code>command</code> <span class="type">String</span> The command to run</li>
<li><code>args</code> <span class="type">Array</span> List of string arguments</li>
<li><code>options</code> <span class="type">Object</span><ul>
<li><code>cwd</code> <span class="type">String</span> Current working directory of the child process</li>
<li><code>stdio</code> <span class="type">Array|String</span> Child's stdio configuration. (See below)</li>
<li><code>customFds</code> <span class="type">Array</span> <strong>Deprecated</strong> File descriptors for the child to use
for stdio. (See below)</li>
<li><code>env</code> <span class="type">Object</span> Environment key-value pairs</li>
<li><code>detached</code> <span class="type">Boolean</span> The child will be a process group leader. (See below)</li>
<li><code>uid</code> <span class="type">Number</span> Sets the user identity of the process. (See setuid(2).)</li>
<li><code>gid</code> <span class="type">Number</span> Sets the group identity of the process. (See setgid(2).)</li>
</ul>
</li>
<li>return: <span class="type">ChildProcess object</span></li>
</div></ul>
<p>Launches a new process with 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>The third argument is used to specify additional options, which defaults to:
</p>
<pre><code>{ cwd: undefined,
env: process.env
}</code></pre>
<p><code>cwd</code> allows you to specify the working directory from which the process is spawned.
Use <code>env</code> to specify environment variables that will be visible to the new process.
</p>
<p>Example of running <code>ls -lh /usr</code>, capturing <code>stdout</code>, <code>stderr</code>, and the exit code:
</p>
<pre><code>var spawn = require('child_process').spawn,
ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.on('data', function (data) {
console.log('stdout: ' + data);
});
ls.stderr.on('data', function (data) {
console.log('stderr: ' + data);
});
ls.on('close', function (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>var spawn = require('child_process').spawn,
ps = spawn('ps', ['ax']),
grep = spawn('grep', ['ssh']);
ps.stdout.on('data', function (data) {
grep.stdin.write(data);
});
ps.stderr.on('data', function (data) {
console.log('ps stderr: ' + data);
});
ps.on('close', function (code) {
if (code !== 0) {
console.log('ps process exited with code ' + code);
}
grep.stdin.end();
});
grep.stdout.on('data', function (data) {
console.log('' + data);
});
grep.stderr.on('data', function (data) {
console.log('grep stderr: ' + data);
});
grep.on('close', function (code) {
if (code !== 0) {
console.log('grep process exited with code ' + code);
}
});</code></pre>
<p>Example of checking for failed exec:
</p>
<pre><code>var spawn = require('child_process').spawn,
child = spawn('bad_command');
child.stderr.setEncoding('utf8');
child.stderr.on('data', function (data) {
if (/^execvp\(\)/.test(data)) {
console.log('Failed to start child process.');
}
});</code></pre>
<p>Note that if spawn receives an empty options object, it will result in
spawning the process with an empty environment rather than using
<code>process.env</code>. This due to backwards compatibility issues with a deprecated
API.
</p>
<p>The 'stdio' option to <code>child_process.spawn()</code> is an array where each
index corresponds to a fd in the 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, then this will
trigger ChildProcess.on('message'). If the child is a Node.js program, then
the presence of an IPC channel will enable process.send() and
process.on('message').</li>
<li><code>'ignore'</code> - Do not set this file descriptor in the child. Note that Node
will always open fd 0 - 2 for the processes it spawns. When any of these is
ignored node will 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>As a shorthand, the <code>stdio</code> argument may also be one of the following
strings, rather than an array:
</p>
<ul>
<li><code>ignore</code> - <code>['ignore', 'ignore', 'ignore']</code></li>
<li><code>pipe</code> - <code>['pipe', 'pipe', 'pipe']</code></li>
<li><code>inherit</code> - <code>[process.stdin, process.stdout, process.stderr]</code> or <code>[0,1,2]</code></li>
</ul>
<p>Example:
</p>
<pre><code>var 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 present a
// startd-style interface.
spawn('prg', [], { stdio: ['pipe', null, null, null, 'pipe'] });</code></pre>
<p>If the <code>detached</code> option is set, the child process will be made the leader of a
new process group. This makes it possible for the child to continue running
after the parent exits.
</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,
and the parent's event loop will not include the child in its reference count.
</p>
<p>Example of detaching a long-running process and redirecting its output to a
file:
</p>
<pre><code> var fs = require('fs'),
spawn = require('child_process').spawn,
out = fs.openSync('./out.log', 'a'),
err = fs.openSync('./out.log', 'a');
var child = spawn('prg', [], {
detached: true,
stdio: [ 'ignore', out, err ]
});
child.unref();</code></pre>
<p>When using the <code>detached</code> option to start a long-running process, the process
will not stay running in the background 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>There is a deprecated option called <code>customFds</code> which allows one to specify
specific file descriptors for the stdio of the child process. This API was
not portable to all platforms and therefore removed.
With <code>customFds</code> it was possible to hook up the new process' <code>[stdin, stdout,
stderr]</code> to existing streams; <code>-1</code> meant that a new stream should be created.
Use at your own risk.
</p>
<p>See also: <code>child_process.exec()</code> and <code>child_process.fork()</code>
</p>
<h2>child_process.exec(command, [options], callback)<span><a class="mark" href="#all_child_process_exec_command_options_callback" id="all_child_process_exec_command_options_callback">#</a></span></h2>
<div class="signature"><ul>
<li><code>command</code> <span class="type">String</span> The command to run, with space-separated arguments</li>
<li><code>options</code> <span class="type">Object</span><ul>
<li><code>cwd</code> <span class="type">String</span> Current working directory of the child process</li>
<li><code>env</code> <span class="type">Object</span> Environment key-value pairs</li>
<li><code>encoding</code> <span class="type">String</span> (Default: 'utf8')</li>
<li><code>timeout</code> <span class="type">Number</span> (Default: 0)</li>
<li><code>maxBuffer</code> <span class="type">Number</span> (Default: <code>200*1024</code>)</li>
<li><code>killSignal</code> <span class="type">String</span> (Default: 'SIGTERM')</li>
</ul>
</li>
<li><code>callback</code> <span class="type">Function</span> called with the output when process terminates<ul>
<li><code>error</code> <span class="type">Error</span></li>
<li><code>stdout</code> <span class="type">Buffer</span></li>
<li><code>stderr</code> <span class="type">Buffer</span></li>
</ul>
</li>
<li>Return: ChildProcess object</li>
</div></ul>
<p>Runs a command in a shell and buffers the output.
</p>
<pre><code>var exec = require('child_process').exec,
child;
child = exec('cat *.js bad_file | wc -l',
function (error, stdout, stderr) {
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
}
});</code></pre>
<p>The callback gets 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 <code>Error</code> and <code>error.code</code>
will be the exit code of the child process, and <code>error.signal</code> will be set to the
signal that terminated the process.
</p>
<p>There is a second optional argument to specify several options. The
default options are
</p>
<pre><code>{ encoding: 'utf8',
timeout: 0,
maxBuffer: 200*1024,
killSignal: 'SIGTERM',
cwd: null,
env: null }</code></pre>
<p>If <code>timeout</code> is greater than 0, then it will kill the child process
if it runs longer than <code>timeout</code> milliseconds. The child process is killed with
<code>killSignal</code> (default: <code>'SIGTERM'</code>). <code>maxBuffer</code> specifies the largest
amount of data allowed on stdout or stderr - if this value is exceeded then
the child process is killed.
</p>
<h2>child_process.execFile(file, [args], [options], [callback])<span><a class="mark" href="#all_child_process_execfile_file_args_options_callback" id="all_child_process_execfile_file_args_options_callback">#</a></span></h2>
<div class="signature"><ul>
<li><code>file</code> <span class="type">String</span> The filename of the program to run</li>
<li><code>args</code> <span class="type">Array</span> List of string arguments</li>
<li><code>options</code> <span class="type">Object</span><ul>
<li><code>cwd</code> <span class="type">String</span> Current working directory of the child process</li>
<li><code>env</code> <span class="type">Object</span> Environment key-value pairs</li>
<li><code>encoding</code> <span class="type">String</span> (Default: 'utf8')</li>
<li><code>timeout</code> <span class="type">Number</span> (Default: 0)</li>
<li><code>maxBuffer</code> <span class="type">Number</span> (Default: 200*1024)</li>
<li><code>killSignal</code> <span class="type">String</span> (Default: 'SIGTERM')</li>
</ul>
</li>
<li><code>callback</code> <span class="type">Function</span> called with the output when process terminates<ul>
<li><code>error</code> <span class="type">Error</span></li>
<li><code>stdout</code> <span class="type">Buffer</span></li>
<li><code>stderr</code> <span class="type">Buffer</span></li>
</ul>
</li>
<li>Return: ChildProcess object</li>
</div></ul>
<p>This is similar to <code>child_process.exec()</code> except it does not execute a
subshell but rather the specified file directly. This makes it slightly
leaner than <code>child_process.exec</code>. It has the same options.
</p>
<h2>child_process.fork(modulePath, [args], [options])<span><a class="mark" href="#all_child_process_fork_modulepath_args_options" id="all_child_process_fork_modulepath_args_options">#</a></span></h2>
<div class="signature"><ul>
<li><code>modulePath</code> <span class="type">String</span> The module to run in the child</li>
<li><code>args</code> <span class="type">Array</span> List of string arguments</li>
<li><code>options</code> <span class="type">Object</span><ul>
<li><code>cwd</code> <span class="type">String</span> Current working directory of the child process</li>
<li><code>env</code> <span class="type">Object</span> Environment key-value pairs</li>
<li><code>encoding</code> <span class="type">String</span> (Default: 'utf8')</li>
<li><code>execPath</code> <span class="type">String</span> Executable used to create the child process</li>
<li><code>execArgv</code> <span class="type">Array</span> List of string arguments passed to the executable
(Default: <code>process.execArgv</code>)</li>
<li><code>silent</code> <span class="type">Boolean</span> 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 "pipe" and "inherit" options for <code>spawn()</code>'s <code>stdio</code> for more details
(default is false)</li>
</ul>
</li>
<li>Return: ChildProcess object</li>
</div></ul>
<p>This is a special case of the <code>spawn()</code> functionality for spawning Node
processes. In addition to having all the methods in a normal ChildProcess
instance, the returned object has a communication channel built-in. See
<code>child.send(message, [sendHandle])</code> for details.
</p>
<p>These child Nodes are still whole new instances of V8. Assume at least 30ms
startup and 10mb memory for each new Node. That is, you cannot create many
thousands of them.
</p>
<p>The <code>execPath</code> property in the <code>options</code> object allows for a process to be
created for the child rather than the current <code>node</code> executable. This should be
done with care and by default will talk over the fd represented an
environmental 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>
<h1>Assert<span><a class="mark" href="#all_assert" id="all_assert">#</a></span></h1>
<pre class="api_stability_5">Stability: 5 - Locked</pre><p>This module is used for writing unit tests for your applications, you can
access it with <code>require('assert')</code>.
</p>
<h2>assert.fail(actual, expected, message, operator)<span><a class="mark" href="#all_assert_fail_actual_expected_message_operator" id="all_assert_fail_actual_expected_message_operator">#</a></span></h2>
<p>Throws an exception that displays the values for <code>actual</code> and <code>expected</code> separated by the provided operator.
</p>
<h2>assert(value, message), assert.ok(value, [message])<span><a class="mark" href="#all_assert_value_message_assert_ok_value_message" id="all_assert_value_message_assert_ok_value_message">#</a></span></h2>
<p>Tests if value is truthy, it is equivalent to <code>assert.equal(true, !!value, message);</code>
</p>
<h2>assert.equal(actual, expected, [message])<span><a class="mark" href="#all_assert_equal_actual_expected_message" id="all_assert_equal_actual_expected_message">#</a></span></h2>
<p>Tests shallow, coercive equality with the equal comparison operator ( <code>==</code> ).
</p>
<h2>assert.notEqual(actual, expected, [message])<span><a class="mark" href="#all_assert_notequal_actual_expected_message" id="all_assert_notequal_actual_expected_message">#</a></span></h2>
<p>Tests shallow, coercive non-equality with the not equal comparison operator ( <code>!=</code> ).
</p>
<h2>assert.deepEqual(actual, expected, [message])<span><a class="mark" href="#all_assert_deepequal_actual_expected_message" id="all_assert_deepequal_actual_expected_message">#</a></span></h2>
<p>Tests for deep equality.
</p>
<h2>assert.notDeepEqual(actual, expected, [message])<span><a class="mark" href="#all_assert_notdeepequal_actual_expected_message" id="all_assert_notdeepequal_actual_expected_message">#</a></span></h2>
<p>Tests for any deep inequality.
</p>
<h2>assert.strictEqual(actual, expected, [message])<span><a class="mark" href="#all_assert_strictequal_actual_expected_message" id="all_assert_strictequal_actual_expected_message">#</a></span></h2>
<p>Tests strict equality, as determined by the strict equality operator ( <code>===</code> )
</p>
<h2>assert.notStrictEqual(actual, expected, [message])<span><a class="mark" href="#all_assert_notstrictequal_actual_expected_message" id="all_assert_notstrictequal_actual_expected_message">#</a></span></h2>
<p>Tests strict non-equality, as determined by the strict not equal operator ( <code>!==</code> )
</p>
<h2>assert.throws(block, [error], [message])<span><a class="mark" href="#all_assert_throws_block_error_message" id="all_assert_throws_block_error_message">#</a></span></h2>
<p>Expects <code>block</code> to throw an error. <code>error</code> can be constructor, <code>RegExp</code> or
validation function.
</p>
<p>Validate instanceof using constructor:
</p>
<pre><code>assert.throws(
function() {
throw new Error("Wrong value");
},
Error
);</code></pre>
<p>Validate error message using RegExp:
</p>
<pre><code>assert.throws(
function() {
throw new Error("Wrong value");
},
/value/
);</code></pre>
<p>Custom error validation:
</p>
<pre><code>assert.throws(
function() {
throw new Error("Wrong value");
},
function(err) {
if ( (err instanceof Error) && /value/.test(err) ) {
return true;
}
},
"unexpected error"
);</code></pre>
<h2>assert.doesNotThrow(block, [message])<span><a class="mark" href="#all_assert_doesnotthrow_block_message" id="all_assert_doesnotthrow_block_message">#</a></span></h2>
<p>Expects <code>block</code> not to throw an error, see <code>assert.throws</code> for details.
</p>
<h2>assert.ifError(value)<span><a class="mark" href="#all_assert_iferror_value" id="all_assert_iferror_value">#</a></span></h2>
<p>Tests if value is not a false value, throws if it is a true value. Useful when
testing the first argument, <code>error</code> in callbacks.
</p>
<h1>TTY<span><a class="mark" href="#all_tty" id="all_tty">#</a></span></h1>
<pre class="api_stability_2">Stability: 2 - Unstable</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 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 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>tty.isatty(fd)<span><a class="mark" href="#all_tty_isatty_fd" id="all_tty_isatty_fd">#</a></span></h2>
<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="#all_tty_setrawmode_mode" id="all_tty_setrawmode_mode">#</a></span></h2>
<p>Deprecated. Use <code>tty.ReadStream#setRawMode()</code>
(i.e. <code>process.stdin.setRawMode()</code>) instead.
</p>
<h2>Class: ReadStream<span><a class="mark" href="#all_class_readstream" id="all_class_readstream">#</a></span></h2>
<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 program (only when <code>isatty(0)</code> is true).
</p>
<h3>rs.isRaw<span><a class="mark" href="#all_rs_israw" id="all_rs_israw">#</a></span></h3>
<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="#all_rs_setrawmode_mode" id="all_rs_setrawmode_mode">#</a></span></h3>
<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="#all_class_writestream" id="all_class_writestream">#</a></span></h2>
<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>ws.columns<span><a class="mark" href="#all_ws_columns" id="all_ws_columns">#</a></span></h3>
<p>A <code>Number</code> that gives the number of columns the TTY currently has. This property
gets updated on "resize" events.
</p>
<h3>ws.rows<span><a class="mark" href="#all_ws_rows" id="all_ws_rows">#</a></span></h3>
<p>A <code>Number</code> that gives the number of rows the TTY currently has. This property
gets updated on "resize" events.
</p>
<h3>Event: 'resize'<span><a class="mark" href="#all_event_resize" id="all_event_resize">#</a></span></h3>
<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>process.stdout.on('resize', function() {
console.log('screen size has changed!');
console.log(process.stdout.columns + 'x' + process.stdout.rows);
});</code></pre>
<h1>Zlib<span><a class="mark" href="#all_zlib" id="all_zlib">#</a></span></h1>
<pre class="api_stability_3">Stability: 3 - Stable</pre><p>You can access this module with:
</p>
<pre><code>var 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="#all_examples" id="all_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>var gzip = zlib.createGzip();
var fs = require('fs');
var inp = fs.createReadStream('input.txt');
var 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>var input = '.................................';
zlib.deflate(input, function(err, buffer) {
if (!err) {
console.log(buffer.toString('base64'));
}
});
var buffer = new Buffer('eJzT0yMAAGTvBe8=', 'base64');
zlib.unzip(buffer, function(err, buffer) {
if (!err) {
console.log(buffer.toString());
}
});</code></pre>
<p>To use this module in an HTTP client or server, use the
<a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3">accept-encoding</a>
on requests, and the
<a href="http://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>
below for more information on the speed/memory/compression
tradeoffs involved in zlib usage.
</p>
<pre><code>// client request example
var zlib = require('zlib');
var http = require('http');
var fs = require('fs');
var request = http.get({ host: 'izs.me',
path: '/',
port: 80,
headers: { 'accept-encoding': 'gzip,deflate' } });
request.on('response', function(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.
var zlib = require('zlib');
var http = require('http');
var fs = require('fs');
http.createServer(function(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>zlib.createGzip([options])<span><a class="mark" href="#all_zlib_creategzip_options" id="all_zlib_creategzip_options">#</a></span></h2>
<p>Returns a new <a href="#zlib_class_zlib_gzip">Gzip</a> object with an
<a href="#zlib_options">options</a>.
</p>
<h2>zlib.createGunzip([options])<span><a class="mark" href="#all_zlib_creategunzip_options" id="all_zlib_creategunzip_options">#</a></span></h2>
<p>Returns a new <a href="#zlib_class_zlib_gunzip">Gunzip</a> object with an
<a href="#zlib_options">options</a>.
</p>
<h2>zlib.createDeflate([options])<span><a class="mark" href="#all_zlib_createdeflate_options" id="all_zlib_createdeflate_options">#</a></span></h2>
<p>Returns a new <a href="#zlib_class_zlib_deflate">Deflate</a> object with an
<a href="#zlib_options">options</a>.
</p>
<h2>zlib.createInflate([options])<span><a class="mark" href="#all_zlib_createinflate_options" id="all_zlib_createinflate_options">#</a></span></h2>
<p>Returns a new <a href="#zlib_class_zlib_inflate">Inflate</a> object with an
<a href="#zlib_options">options</a>.
</p>
<h2>zlib.createDeflateRaw([options])<span><a class="mark" href="#all_zlib_createdeflateraw_options" id="all_zlib_createdeflateraw_options">#</a></span></h2>
<p>Returns a new <a href="#zlib_class_zlib_deflateraw">DeflateRaw</a> object with an
<a href="#zlib_options">options</a>.
</p>
<h2>zlib.createInflateRaw([options])<span><a class="mark" href="#all_zlib_createinflateraw_options" id="all_zlib_createinflateraw_options">#</a></span></h2>
<p>Returns a new <a href="#zlib_class_zlib_inflateraw">InflateRaw</a> object with an
<a href="#zlib_options">options</a>.
</p>
<h2>zlib.createUnzip([options])<span><a class="mark" href="#all_zlib_createunzip_options" id="all_zlib_createunzip_options">#</a></span></h2>
<p>Returns a new <a href="#zlib_class_zlib_unzip">Unzip</a> object with an
<a href="#zlib_options">options</a>.
</p>
<h2>Class: zlib.Zlib<span><a class="mark" href="#all_class_zlib_zlib" id="all_class_zlib_zlib">#</a></span></h2>
<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(callback)<span><a class="mark" href="#all_zlib_flush_callback" id="all_zlib_flush_callback">#</a></span></h3>
<p>Flush pending data. Don't call this frivolously, premature flushes negatively
impact the effectiveness of the compression algorithm.
</p>
<h3>zlib.reset()<span><a class="mark" href="#all_zlib_reset" id="all_zlib_reset">#</a></span></h3>
<p>Reset the compressor/decompressor to factory defaults. Only applicable to
the inflate and deflate algorithms.
</p>
<h2>Class: zlib.Gzip<span><a class="mark" href="#all_class_zlib_gzip" id="all_class_zlib_gzip">#</a></span></h2>
<p>Compress data using gzip.
</p>
<h2>Class: zlib.Gunzip<span><a class="mark" href="#all_class_zlib_gunzip" id="all_class_zlib_gunzip">#</a></span></h2>
<p>Decompress a gzip stream.
</p>
<h2>Class: zlib.Deflate<span><a class="mark" href="#all_class_zlib_deflate" id="all_class_zlib_deflate">#</a></span></h2>
<p>Compress data using deflate.
</p>
<h2>Class: zlib.Inflate<span><a class="mark" href="#all_class_zlib_inflate" id="all_class_zlib_inflate">#</a></span></h2>
<p>Decompress a deflate stream.
</p>
<h2>Class: zlib.DeflateRaw<span><a class="mark" href="#all_class_zlib_deflateraw" id="all_class_zlib_deflateraw">#</a></span></h2>
<p>Compress data using deflate, and do not append a zlib header.
</p>
<h2>Class: zlib.InflateRaw<span><a class="mark" href="#all_class_zlib_inflateraw" id="all_class_zlib_inflateraw">#</a></span></h2>
<p>Decompress a raw deflate stream.
</p>
<h2>Class: zlib.Unzip<span><a class="mark" href="#all_class_zlib_unzip" id="all_class_zlib_unzip">#</a></span></h2>
<p>Decompress either a Gzip- or Deflate-compressed stream by auto-detecting
the header.
</p>
<h2>Convenience Methods<span><a class="mark" href="#all_convenience_methods" id="all_convenience_methods">#</a></span></h2>
<!--type=misc-->
<p>All of these take a string or buffer as the first argument, and call the
supplied callback with <code>callback(error, result)</code>. The
compression/decompression engine is created using the default settings
in all convenience methods. To supply different options, use the
zlib classes directly.
</p>
<h2>zlib.deflate(buf, callback)<span><a class="mark" href="#all_zlib_deflate_buf_callback" id="all_zlib_deflate_buf_callback">#</a></span></h2>
<p>Compress a string with Deflate.
</p>
<h2>zlib.deflateRaw(buf, callback)<span><a class="mark" href="#all_zlib_deflateraw_buf_callback" id="all_zlib_deflateraw_buf_callback">#</a></span></h2>
<p>Compress a string with DeflateRaw.
</p>
<h2>zlib.gzip(buf, callback)<span><a class="mark" href="#all_zlib_gzip_buf_callback" id="all_zlib_gzip_buf_callback">#</a></span></h2>
<p>Compress a string with Gzip.
</p>
<h2>zlib.gunzip(buf, callback)<span><a class="mark" href="#all_zlib_gunzip_buf_callback" id="all_zlib_gunzip_buf_callback">#</a></span></h2>
<p>Decompress a raw Buffer with Gunzip.
</p>
<h2>zlib.inflate(buf, callback)<span><a class="mark" href="#all_zlib_inflate_buf_callback" id="all_zlib_inflate_buf_callback">#</a></span></h2>
<p>Decompress a raw Buffer with Inflate.
</p>
<h2>zlib.inflateRaw(buf, callback)<span><a class="mark" href="#all_zlib_inflateraw_buf_callback" id="all_zlib_inflateraw_buf_callback">#</a></span></h2>
<p>Decompress a raw Buffer with InflateRaw.
</p>
<h2>zlib.unzip(buf, callback)<span><a class="mark" href="#all_zlib_unzip_buf_callback" id="all_zlib_unzip_buf_callback">#</a></span></h2>
<p>Decompress a raw Buffer with Unzip.
</p>
<h2>Options<span><a class="mark" href="#all_options" id="all_options">#</a></span></h2>
<!--type=misc-->
<p>Each class takes an options object. All options are optional. (The
convenience methods use the default settings for all options.)
</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
</p>
<p><a href="http://zlib.net/manual.html#Advanced">http://zlib.net/manual.html#Advanced</a> for more information on these.
</p>
<h2>Memory Usage Tuning<span><a class="mark" href="#all_memory_usage_tuning" id="all_memory_usage_tuning">#</a></span></h2>
<!--type=misc-->
<p>From <code>zlib/zconf.h</code>, modified to node'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 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>Constants<span><a class="mark" href="#all_constants" id="all_constants">#</a></span></h2>
<!--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
</p>
<p><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>Possible values of the data_type field.
</p>
<ul>
<li><code>zlib.Z_BINARY</code></li>
<li><code>zlib.Z_TEXT</code></li>
<li><code>zlib.Z_ASCII</code></li>
<li><code>zlib.Z_UNKNOWN</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>
<h1>os<span><a class="mark" href="#all_os" id="all_os">#</a></span></h1>
<pre class="api_stability_4">Stability: 4 - API Frozen</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.tmpdir()<span><a class="mark" href="#all_os_tmpdir" id="all_os_tmpdir">#</a></span></h2>
<p>Returns the operating system's default directory for temp files.
</p>
<h2>os.endianness()<span><a class="mark" href="#all_os_endianness" id="all_os_endianness">#</a></span></h2>
<p>Returns the endianness of the CPU. Possible values are <code>"BE"</code> or <code>"LE"</code>.
</p>
<h2>os.hostname()<span><a class="mark" href="#all_os_hostname" id="all_os_hostname">#</a></span></h2>
<p>Returns the hostname of the operating system.
</p>
<h2>os.type()<span><a class="mark" href="#all_os_type" id="all_os_type">#</a></span></h2>
<p>Returns the operating system name.
</p>
<h2>os.platform()<span><a class="mark" href="#all_os_platform" id="all_os_platform">#</a></span></h2>
<p>Returns the operating system platform.
</p>
<h2>os.arch()<span><a class="mark" href="#all_os_arch" id="all_os_arch">#</a></span></h2>
<p>Returns the operating system CPU architecture.
</p>
<h2>os.release()<span><a class="mark" href="#all_os_release" id="all_os_release">#</a></span></h2>
<p>Returns the operating system release.
</p>
<h2>os.uptime()<span><a class="mark" href="#all_os_uptime" id="all_os_uptime">#</a></span></h2>
<p>Returns the system uptime in seconds.
</p>
<h2>os.loadavg()<span><a class="mark" href="#all_os_loadavg" id="all_os_loadavg">#</a></span></h2>
<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.totalmem()<span><a class="mark" href="#all_os_totalmem" id="all_os_totalmem">#</a></span></h2>
<p>Returns the total amount of system memory in bytes.
</p>
<h2>os.freemem()<span><a class="mark" href="#all_os_freemem" id="all_os_freemem">#</a></span></h2>
<p>Returns the amount of free system memory in bytes.
</p>
<h2>os.cpus()<span><a class="mark" href="#all_os_cpus" id="all_os_cpus">#</a></span></h2>
<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>[ { 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>
<h2>os.networkInterfaces()<span><a class="mark" href="#all_os_networkinterfaces" id="all_os_networkinterfaces">#</a></span></h2>
<p>Get a list of network interfaces:
</p>
<pre><code>{ lo0:
[ { address: '::1', family: 'IPv6', internal: true },
{ address: 'fe80::1', family: 'IPv6', internal: true },
{ address: '127.0.0.1', family: 'IPv4', internal: true } ],
en1:
[ { address: 'fe80::cabc:c8ff:feef:f996', family: 'IPv6',
internal: false },
{ address: '10.0.1.123', family: 'IPv4', internal: false } ],
vmnet1: [ { address: '10.99.99.254', family: 'IPv4', internal: false } ],
vmnet8: [ { address: '10.88.88.1', family: 'IPv4', internal: false } ],
ppp0: [ { address: '10.2.0.231', family: 'IPv4', internal: false } ] }</code></pre>
<h2>os.EOL<span><a class="mark" href="#all_os_eol" id="all_os_eol">#</a></span></h2>
<p>A constant defining the appropriate End-of-line marker for the operating system.
</p>
<h1>Debugger<span><a class="mark" href="#all_debugger" id="all_debugger">#</a></span></h1>
<pre class="api_stability_3">Stability: 3 - Stable</pre><!-- type=misc -->
<p>V8 comes with an extensive debugger which is accessible out-of-process via a
simple <a href="http://code.google.com/p/v8/wiki/DebuggerProtocol">TCP protocol</a>.
Node has a built-in client for this debugger. To use this, start Node with the
<code>debug</code> argument; a prompt will appear:
</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(function () {
3 debugger;
debug></code></pre>
<p>Node's debugger client doesn't support the full range of commands, but
simple step and inspection is possible. By putting the statement <code>debugger;</code>
into the source code of your script, you will enable a breakpoint.
</p>
<p>For example, suppose <code>myscript.js</code> looked like this:
</p>
<pre><code>// myscript.js
x = 5;
setTimeout(function () {
debugger;
console.log("world");
}, 1000);
console.log("hello");</code></pre>
<p>Then once the debugger is run, it will break on 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(function () {
3 debugger;
debug> cont
< hello
break in /home/indutny/Code/git/indutny/myscript.js:3
1 x = 5;
2 setTimeout(function () {
3 debugger;
4 console.log("world");
5 }, 1000);
debug> next
break in /home/indutny/Code/git/indutny/myscript.js:4
2 setTimeout(function () {
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 you to evaluate code remotely. The <code>next</code> command
steps over to the next line. There are a few other commands available and more
to come. Type <code>help</code> to see others.
</p>
<h2>Watchers<span><a class="mark" href="#all_watchers" id="all_watchers">#</a></span></h2>
<p>You can watch expression and variable values while debugging your code.
On every breakpoint each expression from the watchers list will be evaluated
in the current context and displayed just before the breakpoint's source code
listing.
</p>
<p>To start watching an expression, type <code>watch("my_expression")</code>. <code>watchers</code>
prints the active watchers. To remove a watcher, type
<code>unwatch("my_expression")</code>.
</p>
<h2>Commands reference<span><a class="mark" href="#all_commands_reference" id="all_commands_reference">#</a></span></h2>
<h3>Stepping<span><a class="mark" href="#all_stepping" id="all_stepping">#</a></span></h3>
<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>
<h3>Breakpoints<span><a class="mark" href="#all_breakpoints" id="all_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</code>, <code>cb(...)</code> - Clear breakpoint</li>
</div></ul>
<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 = function() {
23 return 'hello from module';
24 };
25
debug></code></pre>
<h3>Info<span><a class="mark" href="#all_info" id="all_info">#</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>
</div></ul>
<h3>Execution control<span><a class="mark" href="#all_execution_control" id="all_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>
</div></ul>
<h3>Various<span><a class="mark" href="#all_various" id="all_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>
</div></ul>
<h2>Advanced Usage<span><a class="mark" href="#all_advanced_usage" id="all_advanced_usage">#</a></span></h2>
<p>The V8 debugger can be enabled and accessed either by starting Node with
the <code>--debug</code> command-line flag or by signaling an existing Node process
with <code>SIGUSR1</code>.
</p>
<p>Once a process has been set in debug mode with this it can be connected to
with the node debugger. Either connect to the <code>pid</code> or the URI to the debugger.
The syntax is:
</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>
<h1>Cluster<span><a class="mark" href="#all_cluster" id="all_cluster">#</a></span></h1>
<pre class="api_stability_1">Stability: 1 - Experimental</pre><p>A single instance of Node runs in a single thread. To take advantage of
multi-core systems the user will sometimes want to launch a cluster of Node
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>var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
// Fork workers.
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', function(worker, code, signal) {
console.log('worker ' + worker.process.pid + ' died');
});
} else {
// Workers can share any TCP connection
// In this case its a HTTP server
http.createServer(function(req, res) {
res.writeHead(200);
res.end("hello world\n");
}).listen(8000);
}</code></pre>
<p>Running node 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>This feature was introduced recently, and may change in future versions.
Please try it out and provide feedback.
</p>
<p>Also 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="#all_how_it_works" id="all_how_it_works">#</a></span></h2>
<!--type=misc-->
<p>The worker processes are spawned using the <code>child_process.fork</code> method,
so that they can communicate with the parent via IPC and pass server
handles back and forth.
</p>
<p>When you call <code>server.listen(...)</code> in a worker, it serializes the
arguments and passes the request to the master process. If the master
process already has a listening server matching the worker's
requirements, then it passes the handle to the worker. If it does not
already have a listening server matching that requirement, then it will
create one, and pass the handle to the worker.
</p>
<p>This causes potentially surprising behavior in three edge cases:
</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>When multiple processes are all <code>accept()</code>ing on the same underlying
resource, the operating system load-balances across them very
efficiently. 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. Node 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>cluster.settings<span><a class="mark" href="#all_cluster_settings" id="all_cluster_settings">#</a></span></h2>
<div class="signature"><ul>
<li><span class="type">Object</span><ul>
<li><code>execArgv</code> <span class="type">Array</span> list of string arguments passed to the node executable.
(Default=<code>process.execArgv</code>)</li>
<li><code>exec</code> <span class="type">String</span> file path to worker file. (Default=<code>process.argv[1]</code>)</li>
<li><code>args</code> <span class="type">Array</span> string arguments passed to worker.
(Default=<code>process.argv.slice(2)</code>)</li>
<li><code>silent</code> <span class="type">Boolean</span> whether or not to send output to parent's stdio.
(Default=<code>false</code>)</li>
</ul>
</li>
</div></ul>
<p>After calling <code>.setupMaster()</code> (or <code>.fork()</code>) this settings object will contain
the settings, including the default values.
</p>
<p>It is effectively frozen after being set, because <code>.setupMaster()</code> can
only be called once.
</p>
<p>This object is not supposed to be changed or set manually, by you.
</p>
<h2>cluster.isMaster<span><a class="mark" href="#all_cluster_ismaster" id="all_cluster_ismaster">#</a></span></h2>
<div class="signature"><ul>
<li><span class="type">Boolean</span></li>
</div></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="#all_cluster_isworker" id="all_cluster_isworker">#</a></span></h2>
<div class="signature"><ul>
<li><span class="type">Boolean</span></li>
</div></ul>
<p>True if the process is not a master (it is the negation of <code>cluster.isMaster</code>).
</p>
<h2>Event: 'fork'<span><a class="mark" href="#all_event_fork" id="all_event_fork">#</a></span></h2>
<div class="signature"><ul>
<li><code>worker</code> <span class="type">Worker object</span></li>
</div></ul>
<p>When a new worker is forked the cluster module will emit a 'fork' event.
This can be used to log worker activity, and create your own timeout.
</p>
<pre><code>var timeouts = [];
function errorMsg() {
console.error("Something must be wrong with the connection ...");
}
cluster.on('fork', function(worker) {
timeouts[worker.id] = setTimeout(errorMsg, 2000);
});
cluster.on('listening', function(worker, address) {
clearTimeout(timeouts[worker.id]);
});
cluster.on('exit', function(worker, code, signal) {
clearTimeout(timeouts[worker.id]);
errorMsg();
});</code></pre>
<h2>Event: 'online'<span><a class="mark" href="#all_event_online" id="all_event_online">#</a></span></h2>
<div class="signature"><ul>
<li><code>worker</code> <span class="type">Worker object</span></li>
</div></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 'fork' and 'online' is that fork is emitted when the
master forks a worker, and 'online' is emitted when the worker is running.
</p>
<pre><code>cluster.on('online', function(worker) {
console.log("Yay, the worker responded after it was forked");
});</code></pre>
<h2>Event: 'listening'<span><a class="mark" href="#all_event_listening_2" id="all_event_listening_2">#</a></span></h2>
<div class="signature"><ul>
<li><code>worker</code> <span class="type">Worker object</span></li>
<li><code>address</code> <span class="type">Object</span></li>
</div></ul>
<p>After calling <code>listen()</code> from a worker, when the 'listening' event is emitted on
the server, a listening 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>cluster.on('listening', function(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: 'disconnect'<span><a class="mark" href="#all_event_disconnect_1" id="all_event_disconnect_1">#</a></span></h2>
<div class="signature"><ul>
<li><code>worker</code> <span class="type">Worker object</span></li>
</div></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>cluster.on('disconnect', function(worker) {
console.log('The worker #' + worker.id + ' has disconnected');
});</code></pre>
<h2>Event: 'exit'<span><a class="mark" href="#all_event_exit_3" id="all_event_exit_3">#</a></span></h2>
<div class="signature"><ul>
<li><code>worker</code> <span class="type">Worker object</span></li>
<li><code>code</code> <span class="type">Number</span> the exit code, if it exited normally.</li>
<li><code>signal</code> <span class="type">String</span> the name of the signal (eg. <code>'SIGHUP'</code>) that caused
the process to be killed.</li>
</div></ul>
<p>When any of the workers die the cluster module will emit the 'exit' event.
</p>
<p>This can be used to restart the worker by calling <code>.fork()</code> again.
</p>
<pre><code>cluster.on('exit', function(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: 'setup'<span><a class="mark" href="#all_event_setup" id="all_event_setup">#</a></span></h2>
<p>Emitted the first time that <code>.setupMaster()</code> is called.
</p>
<h2>cluster.setupMaster([settings])<span><a class="mark" href="#all_cluster_setupmaster_settings" id="all_cluster_setupmaster_settings">#</a></span></h2>
<div class="signature"><ul>
<li><code>settings</code> <span class="type">Object</span><ul>
<li><code>exec</code> <span class="type">String</span> file path to worker file. (Default=<code>process.argv[1]</code>)</li>
<li><code>args</code> <span class="type">Array</span> string arguments passed to worker.
(Default=<code>process.argv.slice(2)</code>)</li>
<li><code>silent</code> <span class="type">Boolean</span> whether or not to send output to parent's stdio.
(Default=<code>false</code>)</li>
</ul>
</li>
</div></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>Only the first call to <code>.setupMaster()</code> has any effect, subsequent calls are
ignored</li>
<li>That because of the above, the <em>only</em> attribute of a worker that may be
customized per-worker is the <code>env</code> passed to <code>.fork()</code></li>
<li><code>.fork()</code> calls <code>.setupMaster()</code> internally to establish the defaults, so to
have any effect, <code>.setupMaster()</code> must be called <em>before</em> any calls to
<code>.fork()</code></li>
</ul>
<p>Example:
</p>
<pre><code>var cluster = require("cluster");
cluster.setupMaster({
exec : "worker.js",
args : ["--use", "https"],
silent : true
});
cluster.fork();</code></pre>
<p>This can only be called from the master process.
</p>
<h2>cluster.fork([env])<span><a class="mark" href="#all_cluster_fork_env" id="all_cluster_fork_env">#</a></span></h2>
<div class="signature"><ul>
<li><code>env</code> <span class="type">Object</span> Key/value pairs to add to worker process environment.</li>
<li>return <span class="type">Worker object</span></li>
</div></ul>
<p>Spawn a new worker process.
</p>
<p>This can only be called from the master process.
</p>
<h2>cluster.disconnect([callback])<span><a class="mark" href="#all_cluster_disconnect_callback" id="all_cluster_disconnect_callback">#</a></span></h2>
<div class="signature"><ul>
<li><code>callback</code> <span class="type">Function</span> called when all workers are disconnected and handles are
closed</li>
</div></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.worker<span><a class="mark" href="#all_cluster_worker" id="all_cluster_worker">#</a></span></h2>
<div class="signature"><ul>
<li><span class="type">Object</span></li>
</div></ul>
<p>A reference to the current worker object. Not available in the master process.
</p>
<pre><code>var 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="#all_cluster_workers" id="all_cluster_workers">#</a></span></h2>
<div class="signature"><ul>
<li><span class="type">Object</span></li>
</div></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 just before the <code>'disconnect'</code> or
<code>'exit'</code> event is emitted.
</p>
<pre><code>// Go through all workers
function eachWorker(callback) {
for (var id in cluster.workers) {
callback(cluster.workers[id]);
}
}
eachWorker(function(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>socket.on('data', function(id) {
var worker = cluster.workers[id];
});</code></pre>
<h2>Class: Worker<span><a class="mark" href="#all_class_worker" id="all_class_worker">#</a></span></h2>
<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>worker.id<span><a class="mark" href="#all_worker_id" id="all_worker_id">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">String</span></li>
</div></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.process<span><a class="mark" href="#all_worker_process" id="all_worker_process">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">ChildProcess object</span></li>
</div></ul>
<p>All workers are created using <code>child_process.fork()</code>, 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.suicide<span><a class="mark" href="#all_worker_suicide" id="all_worker_suicide">#</a></span></h3>
<div class="signature"><ul>
<li><span class="type">Boolean</span></li>
</div></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>cluster.on('exit', function(worker, code, signal) {
if (worker.suicide === true) {
console.log('Oh, it was just suicide\' – no need to worry').
}
});
// kill worker
worker.kill();</code></pre>
<h3>worker.send(message, [sendHandle])<span><a class="mark" href="#all_worker_send_message_sendhandle" id="all_worker_send_message_sendhandle">#</a></span></h3>
<div class="signature"><ul>
<li><code>message</code> <span class="type">Object</span></li>
<li><code>sendHandle</code> <span class="type">Handle object</span></li>
</div></ul>
<p>This function is equal to the send methods provided by
<code>child_process.fork()</code>. In the master you should use this function to
send a message to a specific worker.
</p>
<p>In a worker you can also use <code>process.send(message)</code>, it is the same function.
</p>
<p>This example will echo back all messages from the master:
</p>
<pre><code>if (cluster.isMaster) {
var worker = cluster.fork();
worker.send('hi there');
} else if (cluster.isWorker) {
process.on('message', function(msg) {
process.send(msg);
});
}</code></pre>
<h3>worker.kill([signal='SIGTERM'])<span><a class="mark" href="#all_worker_kill_signal_sigterm" id="all_worker_kill_signal_sigterm">#</a></span></h3>
<div class="signature"><ul>
<li><code>signal</code> <span class="type">String</span> Name of the kill signal to send to the worker
process.</li>
</div></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">kill</a>.
</p>
<h3>worker.disconnect()<span><a class="mark" href="#all_worker_disconnect" id="all_worker_disconnect">#</a></span></h3>
<p>In a worker, this function will close all servers, wait for the 'close' 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.html#net_event_close">server.close()</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">disconnect</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>if (cluster.isMaster) {
var worker = cluster.fork();
var timeout;
worker.on('listening', function(address) {
worker.send('shutdown');
worker.disconnect();
timeout = setTimeout(function() {
worker.kill();
}, 2000);
});
worker.on('disconnect', function() {
clearTimeout(timeout);
});
} else if (cluster.isWorker) {
var net = require('net');
var server = net.createServer(function(socket) {
// connections never end
});
server.listen(8000);
process.on('message', function(msg) {
if(msg === 'shutdown') {
// initiate graceful close of any connections to server
}
});
}</code></pre>
<h3>Event: 'message'<span><a class="mark" href="#all_event_message_2" id="all_event_message_2">#</a></span></h3>
<div class="signature"><ul>
<li><code>message</code> <span class="type">Object</span></li>
</div></ul>
<p>This event is the same as the one provided by <code>child_process.fork()</code>.
</p>
<p>In a worker you can also use <code>process.on('message')</code>.
</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>var cluster = require('cluster');
var http = require('http');
if (cluster.isMaster) {
// Keep track of http requests
var numReqs = 0;
setInterval(function() {
console.log("numReqs =", numReqs);
}, 1000);
// Count requestes
function messageHandler(msg) {
if (msg.cmd && msg.cmd == 'notifyRequest') {
numReqs += 1;
}
}
// Start workers and listen for messages containing notifyRequest
var numCPUs = require('os').cpus().length;
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
Object.keys(cluster.workers).forEach(function(id) {
cluster.workers[id].on('message', messageHandler);
});
} else {
// Worker processes have a http server.
http.Server(function(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="#all_event_online_1" id="all_event_online_1">#</a></span></h3>
<p>Similar to the <code>cluster.on('online')</code> event, but specific to this worker.
</p>
<pre><code>cluster.fork().on('online', function() {
// Worker is online
});</code></pre>
<p>It is not emitted in the worker.
</p>
<h3>Event: 'listening'<span><a class="mark" href="#all_event_listening_3" id="all_event_listening_3">#</a></span></h3>
<div class="signature"><ul>
<li><code>address</code> <span class="type">Object</span></li>
</div></ul>
<p>Similar to the <code>cluster.on('listening')</code> event, but specific to this worker.
</p>
<pre><code>cluster.fork().on('listening', function(address) {
// Worker is listening
});</code></pre>
<p>It is not emitted in the worker.
</p>
<h3>Event: 'disconnect'<span><a class="mark" href="#all_event_disconnect_2" id="all_event_disconnect_2">#</a></span></h3>
<p>Similar to the <code>cluster.on('disconnect')</code> event, but specfic to this worker.
</p>
<pre><code>cluster.fork().on('disconnect', function() {
// Worker has disconnected
});</code></pre>
<h3>Event: 'exit'<span><a class="mark" href="#all_event_exit_4" id="all_event_exit_4">#</a></span></h3>
<div class="signature"><ul>
<li><code>code</code> <span class="type">Number</span> the exit code, if it exited normally.</li>
<li><code>signal</code> <span class="type">String</span> the name of the signal (eg. <code>'SIGHUP'</code>) that caused
the process to be killed.</li>
</div></ul>
<p>Similar to the <code>cluster.on('exit')</code> event, but specific to this worker.
</p>
<pre><code>var worker = cluster.fork();
worker.on('exit', function(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: 'error'<span><a class="mark" href="#all_event_error_7" id="all_event_error_7">#</a></span></h3>
<p>This event is the same as the one provided by <code>child_process.fork()</code>.
</p>
<p>In a worker you can also use <code>process.on('error')</code>.
</p>
</div>
</div>
</div>
<div id="footer">
<a href="http://joyent.com" class="joyent-logo">Joyent</a>
<ul class="clearfix">
<li><a href="/">Node.js</a></li>
<li><a href="/download/">Download</a></li>
<li><a href="/about/">About</a></li>
<li><a href="http://npmjs.org/">npm Registry</a></li>
<li><a href="http://nodejs.org/api/">Docs</a></li>
<li><a href="http://blog.nodejs.org">Blog</a></li>
<li><a href="/community/">Community</a></li>
<li><a href="/logos/">Logos</a></li>
<li><a href="http://jobs.nodejs.org/">Jobs</a></li>
<li><a href="http://twitter.com/nodejs" class="twitter">@nodejs</a></li>
</ul>
<p>Copyright <a href="http://joyent.com/">Joyent, Inc</a>, Node.js is a <a href="/trademark-policy.pdf">trademark</a> of Joyent, Inc. View <a href="https://raw.github.com/joyent/node/v0.10.29/LICENSE">license</a>.</p>
</div>
<script src="../sh_main.js"></script>
<script src="../sh_javascript.min.js"></script>
<script>highlight(undefined, undefined, 'pre');</script>
<script>
window._gaq = [['_setAccount', 'UA-10874194-2'], ['_trackPageview']];
(function(d, t) {
var g = d.createElement(t),
s = d.getElementsByTagName(t)[0];
g.src = '//www.google-analytics.com/ga.js';
s.parentNode.insertBefore(g, s);
}(document, 'script'));
</script>
</body>
</html>
|