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
|
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta name='generator' value='Ronn/v0.4.1'>
<title>node(1) -- evented I/O for V8 JavaScript</title>
<style type='text/css'>
*{
margin: 0;padding: 0;
}
html,body
{
height: 100%;
}
body
{
font-family:helvetica, arial, sans serif;
background:#22252a;
color:#eee;
font-size:16px;
line-height:1.3;
position:relative;
min-width: 690px;
}
a
{
color:#CD5;
}
a:focus
{
outline: none;
-moz-outline: none;
}
pre
{
overflow: hidden;
}
li
{
list-style: inside;
}
#man,#man code,#man pre,#man tt,#man kbd,#man samp
{
line-height:1.6;
color:#eee;
background:#22252a;
}
#man
{
margin: 0;
position: absolute;
top:0;
bottom:0;
left: 225px;
right: 0;
overflow: auto;
}
#man-content
{
padding: 0 20px;
max-width: 650px;
}
#man h1,#man h2,#man h3
{
color:#DCDDDE;
clear:left;
}
#man h1
{
background:url("http://nodejs.org/logo.png") no-repeat scroll center 0 transparent;
height:111px;
margin:15px 0 20px;
text-align:center;
text-indent:-2000px;
}
#man h2
{
font-size:18px;
background:#000;
color:#CD5;
margin:10px 0;
padding:5px 10px;
}
#man h3
{
font-size:16px;
margin:0 0 0 0ex;
}
#man p,#man ul,#man ol,#man dl,#man pre
{
margin:0 0 18px;
}
#man pre
{
color:#CCCDCE;
background:#121314;
border-left:2ex solid #222;
margin:0 0 20px;
padding:5px 7px;
}
#man pre + h2,#man pre + h3
{
margin-top:22px;
}
#man h2 + pre,#man h3 + pre
{
margin-top:5px;
}
#man > p,#man > ul,#man > ol,#man > dl,#man > pre
{
margin-left:5%;
}
#man dt
{
clear:left;
margin:0;
}
#man dt.flush
{
float:left;
width:8ex;
}
#man dd
{
margin:0 0 0 9ex;
}
#man code,#man strong,#man b
{
font-weight:bold;
color:#ECEDEE;
}
#man pre code
{
font-weight:normal;
color:#DCDDDE;
background:inherit;
}
#man em,var,u
{
font-style:normal;
color:#CCCDCE;
border-bottom:1px solid #999;
}
#man ol.man,#man ol.man li
{
float:left;
width:33%;
list-style-type:none;
text-transform:uppercase;
font-size:18px;
color:#666;
letter-spacing:1px;
margin:2px 0 10px;
padding:0;
}
#man ol.man
{
width:100%;
}
#man ol.man li.tl
{
text-align:left;
}
#man ol.man li.tc
{
text-align:center;
letter-spacing:4px;
}
#man ol.man li.tr
{
text-align:right;
}
#man ol.man a
{
color:#666;
}
#man ol.man a:hover
{
color:#CCCDCE;
}
#toc
{
position: absolute;
top:0;
bottom:0;
left: 0;
padding-left: 30px;
width: 195px;
overflow: auto;
overflow-x: hidden;
font-size: 15px;
}
#toc li
{
text-wrap: word-wrap;
}
#toc a
{
display: inline-block;
width: 100%;
color: #fff;
text-decoration:none;
}
#toc > a:hover
{
color: rgba(255,255,255,0.7);
}
#toc > ul > li
{
border-bottom:1px solid #0f1214;
padding:5px 0 5px 5px;
list-style: none;
line-height: 1.3;
}
#toc ul ul
{
display: none;
}
#toc ul ul > li
{
border-top:1px solid rgba(0, 0, 0, 0.1);
color:#FFFFFF;
font-size:85%;
line-height:1.3;
list-style:disc outside none;
margin-left:25px;
max-width:165px;
padding:3px 0 5px 5px;
}
#toc li.active > a
{
color:#CD5;
}
.sh_sourceCode
{
font-family: monospace;
overflow:hidden;
}
#toc .toggler
{
-moz-user-select:none;
background:none repeat scroll 0 0 #000000;
color:#FFFFFF;
display:inline-block;
font-weight:bold;
height:31px;
line-height:32px;
margin:-5px 8px -18px -33px;
outline:medium none;
padding:0;
text-align:center;
width:25px;
}
.current-section
{
position: fixed;
top: 0;
margin: 0 !important;
}
#toctitle
{
background:none repeat scroll 0 0 #000000;
color:#CCDD55;
font-size:18px;
margin: 0 0 10px -30px;
padding: 10px;
}
</style>
<link rel="stylesheet" href="./sh_vim-dark.css" type="text/css" />
</head>
<body>
<div id="toc">
<div id="toctitle">Node v0.1.99</div>
<noscript>JavaScript must be enabled in your browser to display the table of contents.</noscript>
</div>
<div id='man'>
<div id="man-content">
<h1 class='man-title'>node(1)</h1>
<ol class='head man'>
<li class='tl'>node(1)</li>
<li class='tc'></li>
<li class='tr'>node(1)</li>
</ol>
<h2 id='NAME'>NAME</h2>
<p><code>node</code> -- evented I/O for V8 JavaScript</p>
<h2 id="Synopsis">Synopsis</h2>
<p>An example of a web server written with Node which responds with 'Hello
World':</p>
<pre><code>var sys = require('sys'),
http = require('http');
http.createServer(function (request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Hello World\n');
}).listen(8124);
sys.puts('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>
<h2 id="Standard Modules">Standard Modules</h2>
<p>Node comes with a number of modules that are compiled in to the process,
most of which are documented below. The most common way to use these modules
is with <code>require('name')</code> and then assigning the return value to a local
variable with the same name as the module.</p>
<p>Example:</p>
<pre><code>var sys = require('sys');
</code></pre>
<p>It is possible to extend node with other modules. See <code>'Modules'</code></p>
<h2 id="Buffers">Buffers</h2>
<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.
Access the class with <code>require('buffer').Buffer</code>.</p>
<p>Converting between Buffers and JavaScript string objects requires an explicit encoding
method. Node supports 3 string encodings: UTF-8 (<code>'utf8'</code>), ASCII (<code>'ascii'</code>), and
Binary (<code>'binary'</code>).</p>
<ul>
<li><p><code>'ascii'</code> - for 7 bit ASCII data only. This encoding method is very fast, and will
strip the high bit if set.</p></li>
<li><p><code>'binary'</code> - for 8 bit binary data such as images.</p></li>
<li><p><code>'utf8'</code> - Unicode characters. Many web pages and other document formats use UTF-8.</p></li>
</ul>
<h3>new Buffer(size)</h3>
<p>Allocates a new buffer of <code>size</code> octets.</p>
<h3>new Buffer(array)</h3>
<p>Allocates a new buffer using an <code>array</code> of octets.</p>
<h3>new Buffer(str, encoding = 'utf8')</h3>
<p>Allocates a new buffer containing the given <code>str</code>.</p>
<h3>buffer.write(string, encoding, offset)</h3>
<p>Writes <code>string</code> to the buffer at <code>offset</code> using the given encoding. 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. In the case
of <code>'utf8'</code> encoding, the method will not write partial characters.</p>
<p>Example: write a utf8 string into a buffer, then print it</p>
<pre><code>var sys = require('sys'),
Buffer = require('buffer').Buffer,
buf = new Buffer(256),
len;
len = buf.write('\u00bd + \u00bc = \u00be', 'utf8', 0);
sys.puts(len + " bytes: " + buf.toString('utf8', 0, len));
// 12 bytes: ½ + ¼ = ¾
</code></pre>
<h3>buffer.toString(encoding, start, end)</h3>
<p>Decodes and returns a string from buffer data encoded with <code>encoding</code>
beginning at <code>start</code> and ending at <code>end</code>.</p>
<p>See <code>buffer.write()</code> example, above.</p>
<h3>buffer[index]</h3>
<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>var sys = require('sys'),
Buffer = require('buffer').Buffer,
str = "node.js",
buf = new Buffer(str.length),
i;
for (i = 0; i < str.length ; i += 1) {
buf[i] = str.charCodeAt(i);
}
sys.puts(buf);
// node.js
</code></pre>
<h3>Buffer.byteLength(string, encoding)</h3>
<p>Gives the actual byte length of a string. 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>var sys = require('sys'),
Buffer = require('buffer').Buffer,
str = '\u00bd + \u00bc = \u00be';
sys.puts(str + ": " + str.length + " characters, " +
Buffer.byteLength(str, 'utf8') + " bytes");
// ½ + ¼ = ¾: 9 characters, 12 bytes
</code></pre>
<h3>buffer.length</h3>
<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>var sys = require('sys'),
Buffer = require('buffer').Buffer,
buf = new Buffer(1234);
sys.puts(buf.length);
buf.write("some string", "ascii", 0);
sys.puts(buf.length);
// 1234
// 1234
</code></pre>
<h3>buffer.copy(targetBuffer, targetStart, sourceStart, sourceEnd)</h3>
<p>Does a memcpy() between buffers.</p>
<p>Example: build two Buffers, then copy <code>buf1</code> from byte 16 through byte 20
into <code>buf2</code>, starting at the 8th byte in <code>buf2</code>.</p>
<pre><code>var sys = require('sys'),
Buffer = require('buffer').Buffer,
buf1 = new Buffer(26),
buf2 = new Buffer(26),
i;
for (i = 0 ; i < 26 ; i += 1) {
buf1[i] = i + 97; // 97 is ASCII a
buf2[i] = 33; // ASCII !
}
buf1.copy(buf2, 8, 16, 20);
sys.puts(buf2.toString('ascii', 0, 25));
// !!!!!!!!qrst!!!!!!!!!!!!!
</code></pre>
<h3>buffer.slice(start, end)</h3>
<p>Returns a new buffer which references the
same memory as the old, but offset and cropped by the <code>start</code> and <code>end</code>
indexes.</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 sys = require('sys'),
Buffer = require('buffer').Buffer,
buf1 = new Buffer(26), buf2,
i;
for (i = 0 ; i < 26 ; i += 1) {
buf1[i] = i + 97; // 97 is ASCII a
}
buf2 = buf1.slice(0, 3);
sys.puts(buf2.toString('ascii', 0, buf2.length));
buf1[0] = 33;
sys.puts(buf2.toString('ascii', 0, buf2.length));
// abc
// !bc
</code></pre>
<h2 id="EventEmitter">EventEmitter</h2>
<p>Many objects in Node emit events: a TCP server emits an event each time
there is a stream, a child process emits an event when it exits. All
objects which emit events are instances of <code>events.EventEmitter</code>.</p>
<p>Events are represented by a camel-cased string. Here are some examples:
<code>'stream'</code>, <code>'data'</code>, <code>'messageBegin'</code>.</p>
<p>Functions can be then be attached to objects, to be executed when an event
is emitted. These functions are called <em>listeners</em>.</p>
<p><code>require('events').EventEmitter</code> to access the <code>EventEmitter</code> class.</p>
<p>All EventEmitters emit the event <code>'newListener'</code> when new listeners are
added.</p>
<p>When an EventEmitter experiences an error, the typical action is to emit an
<code>'error'</code> event. Error events are special--if there is no handler for them
they will print a stack trace and exit the program.</p>
<h3>Event: 'newListener'</h3>
<p><code>function (event, listener) { }</code></p>
<p>This event is made any time someone adds a new listener.</p>
<h3>Event: 'error'</h3>
<p><code>function (exception) { }</code></p>
<p>If an error was encountered, then this event is emitted. This event is
special - when there are no listeners to receive the error Node will
terminate execution and display the exception's stack trace.</p>
<h3>emitter.addListener(event, listener)</h3>
<p>Adds a listener to the end of the listeners array for the specified event.</p>
<pre><code>server.addListener('stream', function (stream) {
sys.puts('someone connected!');
});
</code></pre>
<h3>emitter.removeListener(event, listener)</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>
<h3>emitter.removeAllListeners(event)</h3>
<p>Removes all listeners from the listener array for the specified event.</p>
<h3>emitter.listeners(event)</h3>
<p>Returns an array of listeners for the specified event. This array can be
manipulated, e.g. to remove listeners.</p>
<h3>emitter.emit(event, arg1, arg2, ...)</h3>
<p>Execute each of the listeners in order with the supplied arguments.</p>
<h2 id="Streams">Streams</h2>
<p>A stream is an abstract interface implemented by various objects in Node.
For example a request to an HTTP server is a stream, as is stdout. Streams
are readable, writable, or both. All streams are instances of <code>EventEmitter</code>.</p>
<h2 id="Readable Stream">Readable Stream</h2>
<p>A <strong>readable stream</strong> has the following methods, members, and events.</p>
<h3>Event: 'data'</h3>
<p><code>function (data) { }</code></p>
<p>The <code>'data'</code> event emits either a <code>Buffer</code> (by default) or a string if
<code>setEncoding()</code> was used.</p>
<h3>Event: 'end'</h3>
<p><code>function () { }</code></p>
<p>Emitted when the stream has received an EOF (FIN in TCP terminology).
Indicates that no more <code>'data'</code> events will happen. If the stream is also
writable, it may be possible to continue writing.</p>
<h3>Event: 'error'</h3>
<p><code>function (exception) { }</code></p>
<p>Emitted if there was an error receiving data.</p>
<h3>Event: 'close'</h3>
<p><code>function () { }</code></p>
<p>Emitted when the underlying file descriptor has be closed. Not all streams
will emit this. (For example, an incoming HTTP request will not emit
<code>'close'</code>.)</p>
<h3>stream.setEncoding(encoding)</h3>
<p>Makes the data event emit a string instead of a <code>Buffer</code>. <code>encoding</code> can be
<code>'utf8'</code>, <code>'ascii'</code>, or <code>'binary'</code>.</p>
<h3>stream.pause()</h3>
<p>Pauses the incoming <code>'data'</code> events.</p>
<h3>stream.resume()</h3>
<p>Resumes the incoming <code>'data'</code> events after a <code>pause()</code>.</p>
<h3>stream.destroy()</h3>
<p>Closes the underlying file descriptor. Stream will not emit any more events.</p>
<h2 id="Writable Stream">Writable Stream</h2>
<p>A <strong>writable stream</strong> has the following methods, members, and events.</p>
<h3>Event: 'drain'</h3>
<p><code>function () { }</code></p>
<p>Emitted after a <code>write()</code> method was called that returned <code>false</code> to
indicate that it is safe to write again.</p>
<h3>Event: 'error'</h3>
<p><code>function (exception) { }</code></p>
<p>Emitted on error with the exception <code>exception</code>.</p>
<h3>Event: 'close'</h3>
<p><code>function () { }</code></p>
<p>Emitted when the underlying file descriptor has been closed.</p>
<h3>stream.write(string, encoding)</h3>
<p>Writes <code>string</code> with the given <code>encoding</code> to the stream. Returns <code>true</code> if
the string has been flushed to the kernel buffer. Returns <code>false</code> to
indicate that the kernel buffer is full, and the data will be sent out in
the future. The <code>'drain'</code> event will indicate when the kernel buffer is
empty again. The <code>encoding</code> defaults to <code>'utf8'</code>.</p>
<h3>stream.write(buffer)</h3>
<p>Same as the above except with a raw buffer.</p>
<h3>stream.end()</h3>
<p>Terminates the stream with EOF or FIN.</p>
<h3>stream.end(string, encoding)</h3>
<p>Sends <code>string</code> with the given <code>encoding</code> and terminates the stream with EOF
or FIN. This is useful to reduce the number of packets sent.</p>
<h3>stream.end(buffer)</h3>
<p>Same as above but with a <code>buffer</code>.</p>
<h3>stream.destroy()</h3>
<p>Closes the underlying file descriptor. Stream will not emit any more events.</p>
<h2 id="Global Objects">Global Objects</h2>
<p>These object are available in the global scope and can be accessed from anywhere.</p>
<h3>global</h3>
<p>The global namespace object.</p>
<h3>process</h3>
<p>The process object. Most stuff lives in here. See the <code>'process object'</code>
section.</p>
<h3>require()</h3>
<p>To require modules. See the <code>'Modules'</code> section.</p>
<h3>require.paths</h3>
<p>An array of search paths for <code>require()</code>. This array can be modified to add custom paths.</p>
<p>Example: add a new path to the beginning of the search list</p>
<pre><code>var sys = require('sys');
require.paths.unshift('/usr/local/node');
sys.puts(require.paths);
// /usr/local/node,/Users/mjr/.node_libraries
</code></pre>
<h3>__filename</h3>
<p>The filename of the script being executed. This is the absolute path, and not necessarily
the same filename passed in as a command line argument.</p>
<h3>__dirname</h3>
<p>The dirname of the script being executed.</p>
<p>Example: running <code>node example.js</code> from <code>/Users/mjr</code></p>
<pre><code>var sys = require('sys');
sys.puts(__filename);
sys.puts(__dirname);
// /Users/mjr/example.js
// /Users/mjr
</code></pre>
<h3>module</h3>
<p>A reference to the current module (of type <code>process.Module</code>). In particular
<code>module.exports</code> is the same as the <code>exports</code> object. See <code>src/process.js</code>
for more information.</p>
<h2 id="process">process</h2>
<p>The <code>process</code> object is a global object and can be accessed from anywhere.
It is an instance of <code>EventEmitter</code>.</p>
<h3>Event: 'exit'</h3>
<p><code>function () {}</code></p>
<p>Emitted when the process is about to exit. This is a good hook to perform
constant time checks of the module's state (like for unit tests). The main
event loop will no longer be run after the 'exit' callback finishes, so
timers may not be scheduled.</p>
<p>Example of listening for <code>exit</code>:</p>
<pre><code>var sys = require('sys');
process.addListener('exit', function () {
process.nextTick(function () {
sys.puts('This will not run');
});
sys.puts('About to exit.');
});
</code></pre>
<h3>Event: 'uncaughtException'</h3>
<p><code>function (err) { }</code></p>
<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>var sys = require('sys');
process.addListener('uncaughtException', function (err) {
sys.puts('Caught exception: ' + err);
});
setTimeout(function () {
sys.puts('This will still run.');
}, 500);
// Intentionally cause an exception, but don't catch it.
nonexistentFunc();
sys.puts('This will not run.');
</code></pre>
<p>Note that <code>uncaughtException</code> is a very crude mechanism for exception
handling. Using try / catch in your program will give you more control over
your program's flow. Especially for server programs that are designed to
stay running forever, <code>uncaughtException</code> can be a useful safety mechanism.</p>
<h3>Signal Events</h3>
<p><code>function () {}</code></p>
<p>Emitted when the processes receives a signal. See sigaction(2) for a list of
standard POSIX signal names such as SIGINT, SIGUSR1, etc.</p>
<p>Example of listening for <code>SIGINT</code>:</p>
<pre><code>var sys = require('sys'),
stdin = process.openStdin();
process.addListener('SIGINT', function () {
sys.puts('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>
<h3>process.stdout</h3>
<p>A writable stream to <code>stdout</code>.</p>
<p>Example: the definition of <code>sys.puts</code></p>
<pre><code>exports.puts = function (d) {
process.stdout.write(d + '\n');
};
</code></pre>
<h3>process.openStdin()</h3>
<p>Opens the standard input stream, returns a readable stream.</p>
<p>Example of opening standard input and listening for both events:</p>
<pre><code>var stdin = process.openStdin();
stdin.setEncoding('utf8');
stdin.addListener('data', function (chunk) {
process.stdout.write('data: ' + chunk);
});
stdin.addListener('end', function () {
process.stdout.write('end');
});
</code></pre>
<h3>process.argv</h3>
<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
var sys = require('sys');
process.argv.forEach(function (val, index, array) {
sys.puts(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>
<h3>process.chdir(directory)</h3>
<p>Changes the current working directory of the process or throws an exception if that fails.</p>
<pre><code>var sys = require('sys');
sys.puts('Starting directory: ' + process.cwd());
try {
process.chdir('/tmp');
sys.puts('New directory: ' + process.cwd());
}
catch (err) {
sys.puts('chdir: ' + err);
}
</code></pre>
<h3>process.compile(code, filename)</h3>
<p>Similar to <code>eval</code> except that you can specify a <code>filename</code> for better
error reporting and the <code>code</code> cannot see the local scope. The value of <code>filename</code>
will be used as a filename if a stack trace is generated by the compiled code.</p>
<p>Example of using <code>process.compile</code> and <code>eval</code> to run the same code:</p>
<pre><code>var sys = require('sys'),
localVar = 123,
compiled, evaled;
compiled = process.compile('localVar = 1;', 'myfile.js');
sys.puts('localVar: ' + localVar + ', compiled: ' + compiled);
evaled = eval('localVar = 1;');
sys.puts('localVar: ' + localVar + ', evaled: ' + evaled);
// localVar: 123, compiled: 1
// localVar: 1, evaled: 1
</code></pre>
<p><code>process.compile</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>process.compile</code> exits node.</p>
<p>See also: <code>Script</code></p>
<h3>process.cwd()</h3>
<p>Returns the current working directory of the process.</p>
<pre><code>require('sys').puts('Current directory: ' + process.cwd());
</code></pre>
<h3>process.env</h3>
<p>An object containing the user environment. See environ(7).</p>
<h3>process.exit(code)</h3>
<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>
<h3>process.getgid(), process.setgid(id)</h3>
<p>Gets/sets the group identity of the process. (See setgid(2).) This is the numerical group id, not the group name.</p>
<pre><code>var sys = require('sys');
sys.puts('Current gid: ' + process.getgid());
try {
process.setgid(501);
sys.puts('New gid: ' + process.getgid());
}
catch (err) {
sys.puts('Failed to set gid: ' + err);
}
</code></pre>
<h3>process.getuid(), process.setuid(id)</h3>
<p>Gets/sets the user identity of the process. (See setuid(2).) This is the numerical userid, not the username.</p>
<pre><code>var sys = require('sys');
sys.puts('Current uid: ' + process.getuid());
try {
process.setuid(501);
sys.puts('New uid: ' + process.getuid());
}
catch (err) {
sys.puts('Failed to set uid: ' + err);
}
</code></pre>
<h3>process.version</h3>
<p>A compiled-in property that exposes <code>NODE_VERSION</code>.</p>
<pre><code>require('sys').puts('Version: ' + process.version);
</code></pre>
<h3>process.installPrefix</h3>
<p>A compiled-in property that exposes <code>NODE_PREFIX</code>.</p>
<pre><code>require('sys').puts('Prefix: ' + process.installPrefix);
</code></pre>
<h3>process.kill(pid, signal)</h3>
<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 'SIGUSR1'. If omitted, the signal will be 'SIGINT'.
See kill(2) for more information.</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>var sys = require('sys');
process.addListener('SIGHUP', function () {
sys.puts('Got SIGHUP signal.');
});
setTimeout(function () {
sys.puts('Exiting.');
process.exit(0);
}, 100);
process.kill(process.pid, 'SIGHUP');
</code></pre>
<h3>process.pid</h3>
<p>The PID of the process.</p>
<pre><code>require('sys').puts('This process is pid ' + process.pid);
</code></pre>
<h3>process.platform</h3>
<p>What platform you're running on. <code>'linux2'</code>, <code>'darwin'</code>, etc.</p>
<pre><code>require('sys').puts('This platform is ' + process.platform);
</code></pre>
<h3>process.memoryUsage()</h3>
<p>Returns an object describing the memory usage of the Node process.</p>
<pre><code>var sys = require('sys');
sys.puts(sys.inspect(process.memoryUsage()));
</code></pre>
<p>This will generate:</p>
<pre><code>{ rss: 4935680
, vsize: 41893888
, heapTotal: 1826816
, heapUsed: 650472
}
</code></pre>
<p><code>heapTotal</code> and <code>heapUsed</code> refer to V8's memory usage.</p>
<h3>process.nextTick(callback)</h3>
<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.</p>
<pre><code>var sys = require('sys');
process.nextTick(function () {
sys.puts('nextTick callback');
});
</code></pre>
<h3>process.umask(mask)</h3>
<p>Sets or read 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 sys = require('sys'),
oldmask, newmask = 0644;
oldmask = process.umask(newmask);
sys.puts('Changed umask from: ' + oldmask.toString(8) +
' to ' + newmask.toString(8));
</code></pre>
<h2 id="sys">sys</h2>
<p>These functions are in the module <code>'sys'</code>. Use <code>require('sys')</code> to access
them.</p>
<h3>sys.puts(string)</h3>
<p>Outputs <code>string</code> and a trailing newline to <code>stdout</code>.</p>
<pre><code>require('sys').puts('String with a newline');
</code></pre>
<h3>sys.print(string)</h3>
<p>Like <code>puts()</code> but without the trailing newline.</p>
<pre><code>require('sys').print('String with no newline');
</code></pre>
<h3>sys.debug(string)</h3>
<p>A synchronous output function. Will block the process and
output <code>string</code> immediately to <code>stderr</code>.</p>
<pre><code>require('sys').debug('message on stderr');
</code></pre>
<h3>sys.log(string)</h3>
<p>Output with timestamp on <code>stdout</code>.</p>
<pre><code>require('sys').log('Timestmaped message.');
</code></pre>
<h3>sys.inspect(object, showHidden, depth)</h3>
<p>Return a string representation of <code>object</code>, which is useful for debugging.</p>
<p>If <code>showHidden</code> is <code>true</code>, then the object's non-enumerable properties will be
shown too.</p>
<p>If <code>depth</code> is provided, it tells <code>inspect</code> how many times to recurse while
formatting the object. This is useful for inspecting large complicated objects.</p>
<p>The default is to only recurse twice. To make it recurse indefinitely, pass
in <code>null</code> for <code>depth</code>.</p>
<p>Example of inspecting all properties of the <code>sys</code> object:</p>
<pre><code>var sys = require('sys');
sys.puts(sys.inspect(sys, true, null));
</code></pre>
<h2 id="Timers">Timers</h2>
<h3>setTimeout(callback, delay, [arg, ...])</h3>
<p>To schedule execution of <code>callback</code> after <code>delay</code> milliseconds. Returns a
<code>timeoutId</code> for possible use with <code>clearTimeout()</code>.</p>
<h3>clearTimeout(timeoutId)</h3>
<p>Prevents a timeout from triggering.</p>
<h3>setInterval(callback, delay, [arg, ...])</h3>
<p>To schedule the repeated execution of <code>callback</code> every <code>delay</code> milliseconds.
Returns a <code>intervalId</code> for possible use with <code>clearInterval()</code>.</p>
<p>Optionally, you can also pass arguments to the callback.</p>
<h3>clearInterval(intervalId)</h3>
<p>Stops a interval from triggering.</p>
<h2 id="Child Processes">Child Processes</h2>
<p>Node provides a tri-directional <code>popen(3)</code> facility through the <code>ChildProcess</code>
class.</p>
<p>It is possible to stream data through the child's <code>stdin</code>, <code>stdout</code>, and
<code>stderr</code> in a fully non-blocking way.</p>
<p>To create a child process use <code>require('child_process').spawn()</code>.</p>
<p>Child processes always have three streams associated with them. <code>child.stdin</code>,
<code>child.stdout</code>, and <code>child.stderr</code>.</p>
<p><code>ChildProcess</code> is an EventEmitter.</p>
<h3>Event: 'exit'</h3>
<p><code>function (code, signal) {}</code></p>
<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>After this event is emitted, the <code>'output'</code> and <code>'error'</code> callbacks will no
longer be made.</p>
<p>See <code>waitpid(2)</code>.</p>
<h3>child_process.spawn(command, args, env)</h3>
<p>Launches a new process with the given <code>command</code>, command line arguments, and
environment variables. If omitted, <code>args</code> defaults to an empty Array, and <code>env</code>
defaults to <code>process.env</code>.</p>
<p>Example of running <code>ls -lh /usr</code>, capturing <code>stdout</code>, <code>stderr</code>, and the exit code:</p>
<pre><code>var sys = require('sys'),
spawn = require('child_process').spawn,
ls = spawn('ls', ['-lh', '/usr']);
ls.stdout.addListener('data', function (data) {
sys.print('stdout: ' + data);
});
ls.stderr.addListener('data', function (data) {
sys.print('stderr: ' + data);
});
ls.addListener('exit', function (code) {
sys.puts('child process exited with code ' + code);
});
</code></pre>
<p>Example of checking for failed exec:</p>
<pre><code>var sys = require('sys'),
spawn = require('child_process').spawn,
child = spawn('bad_command');
child.stderr.addListener('data', function (data) {
if (/^execvp\(\)/.test(data.asciiSlice(0,data.length))) {
sys.puts('Failed to start child process.');
}
});
</code></pre>
<p>See also: <code>child_process.exec()</code></p>
<h3>child.kill(signal)</h3>
<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 sys = require('sys'),
spawn = require('child_process').spawn,
grep = spawn('grep', ['ssh']);
grep.addListener('exit', function (code, signal) {
sys.puts('child process terminated due to receipt of signal '+signal);
});
// send SIGHUP to process
grep.kill('SIGHUP');
</code></pre>
<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.pid</h3>
<p>The PID of the child process.</p>
<p>Example:</p>
<pre><code>var sys = require('sys'),
spawn = require('child_process').spawn,
grep = spawn('grep', ['ssh']);
sys.puts('Spawned child pid: ' + grep.pid);
grep.stdin.end();
</code></pre>
<h3>child.stdin.write(data, encoding)</h3>
<p>Write data to the child process's <code>stdin</code>. The second argument is optional and
specifies the encoding: possible values are <code>'utf8'</code>, <code>'ascii'</code>, and
<code>'binary'</code>.</p>
<p>Example: A very elaborate way to run 'ps ax | grep ssh'</p>
<pre><code>var sys = require('sys'),
spawn = require('child_process').spawn,
ps = spawn('ps', ['ax']),
grep = spawn('grep', ['ssh']);
ps.stdout.addListener('data', function (data) {
grep.stdin.write(data);
});
ps.stderr.addListener('data', function (data) {
sys.print('ps stderr: ' + data);
});
ps.addListener('exit', function (code) {
if (code !== 0) {
sys.puts('ps process exited with code ' + code);
}
grep.stdin.end();
});
grep.stdout.addListener('data', function (data) {
sys.print(data);
});
grep.stderr.addListener('data', function (data) {
sys.print('grep stderr: ' + data);
});
grep.addListener('exit', function (code) {
if (code !== 0) {
sys.puts('grep process exited with code ' + code);
}
});
</code></pre>
<h3>child.stdin.end()</h3>
<p>Closes the child process's <code>stdin</code> stream. This often causes the child process to terminate.</p>
<p>Example:</p>
<pre><code>var sys = require('sys'),
spawn = require('child_process').spawn,
grep = spawn('grep', ['ssh']);
grep.addListener('exit', function (code) {
sys.puts('child process exited with code ' + code);
});
grep.stdin.end();
</code></pre>
<h3>child_process.exec(command, [options, ] callback)</h3>
<p>High-level way to execute a command as a child process, buffer the
output, and return it all in a callback.</p>
<pre><code>var sys = require('sys'),
exec = require('child_process').exec,
child;
child = exec('cat *.js bad_file | wc -l',
function (error, stdout, stderr) {
sys.print('stdout: ' + stdout);
sys.print('stderr: ' + stderr);
if (error !== null) {
sys.puts('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>err.code</code>
will be the exit code of the child process, and <code>err.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: 'SIGKILL'
}
</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>'SIGKILL'</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 id="Script">Script</h2>
<p><code>Script</code> class compiles and runs JavaScript code. You can access this class with:</p>
<pre><code>var Script = process.binding('evals').Script;
</code></pre>
<p>New JavaScript code can be compiled and run immediately or compiled, saved, and run later.</p>
<h3>Script.runInThisContext(code, filename)</h3>
<p>Similar to <code>process.compile</code>. <code>Script.runInThisContext</code> compiles <code>code</code> as if it were loaded from <code>filename</code>,
runs it and returns the result. Running code does not have access to local scope. <code>filename</code> is optional.</p>
<p>Example of using <code>Script.runInThisContext</code> and <code>eval</code> to run the same code:</p>
<pre><code>var sys = require('sys'),
localVar = 123,
usingscript, evaled,
Script = process.binding('evals').Script;
usingscript = Script.runInThisContext('localVar = 1;',
'myfile.js');
sys.puts('localVar: ' + localVar + ', usingscript: ' +
usingscript);
evaled = eval('localVar = 1;');
sys.puts('localVar: ' + localVar + ', evaled: ' +
evaled);
// localVar: 123, usingscript: 1
// localVar: 1, evaled: 1
</code></pre>
<p><code>Script.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>Script.runInThisContext</code> emits the syntax error to stderr
and throws.an exception.</p>
<h3>Script.runInNewContext(code, sandbox, filename)</h3>
<p><code>Script.runInNewContext</code> compiles <code>code</code> to run in <code>sandbox</code> as if it were loaded from <code>filename</code>,
then runs it and returns the result. Running code does not have access to local scope and
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.</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 sys = require('sys'),
Script = process.binding('evals').Script,
sandbox = {
animal: 'cat',
count: 2
};
Script.runInNewContext(
'count += 1; name = "kitty"', sandbox, 'myfile.js');
sys.puts(sys.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>Script.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>Script.runInThisContext</code> emits the syntax error to stderr
and throws an exception.</p>
<h3>new Script(code, filename)</h3>
<p><code>new Script</code> compiles <code>code</code> as if it were loaded from <code>filename</code>,
but does not run it. Instead, it returns a <code>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.</p>
<p>In case of syntax error in <code>code</code>, <code>new Script</code> emits the syntax error to stderr
and throws an exception.</p>
<h3>script.runInThisContext()</h3>
<p>Similar to <code>Script.runInThisContext</code> (note capital 'S'), but now being a method of a precompiled Script 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 sys = require('sys'),
Script = process.binding('evals').Script,
scriptObj, i;
globalVar = 0;
scriptObj = new Script('globalVar += 1', 'myfile.js');
for (i = 0; i < 1000 ; i += 1) {
scriptObj.runInThisContext();
}
sys.puts(globalVar);
// 1000
</code></pre>
<h3>script.runInNewContext(sandbox)</h3>
<p>Similar to <code>Script.runInNewContext</code> (note capital 'S'), but now being a method of a precompiled Script 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 sys = require('sys'),
Script = process.binding('evals').Script,
scriptObj, i,
sandbox = {
animal: 'cat',
count: 2
};
scriptObj = new Script(
'count += 1; name = "kitty"', 'myfile.js');
for (i = 0; i < 10 ; i += 1) {
scriptObj.runInNewContext(sandbox);
}
sys.puts(sys.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>
<h2 id="File System">File System</h2>
<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>Here is an example of the asynchronous version:</p>
<pre><code>var fs = require('fs'),
sys = require('sys');
fs.unlink('/tmp/hello', function (err) {
if (err) throw err;
sys.puts('successfully deleted /tmp/hello');
});
</code></pre>
<p>Here is the synchronous version:</p>
<pre><code>var fs = require('fs'),
sys = require('sys');
fs.unlinkSync('/tmp/hello')
sys.puts('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;
sys.puts('renamed complete');
});
fs.stat('/tmp/world', function (err, stats) {
if (err) throw err;
sys.puts('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;
sys.puts('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>
<h3>fs.rename(path1, path2, callback)</h3>
<p>Asynchronous rename(2). No arguments other than a possible exception are given to the completion callback.</p>
<h3>fs.renameSync(path1, path2)</h3>
<p>Synchronous rename(2).</p>
<h3>fs.truncate(fd, len, callback)</h3>
<p>Asynchronous ftruncate(2). No arguments other than a possible exception are given to the completion callback.</p>
<h3>fs.truncateSync(fd, len)</h3>
<p>Synchronous ftruncate(2).</p>
<h3>fs.chmod(path, mode, callback)</h3>
<p>Asynchronous chmod(2). No arguments other than a possible exception are given to the completion callback.</p>
<h3>fs.chmodSync(path, mode)</h3>
<p>Synchronous chmod(2).</p>
<h3>fs.stat(path, callback), fs.lstat(path, callback), fs.fstat(fd, callback)</h3>
<p>Asynchronous stat(2), lstat(2) or fstat(2). The callback gets two arguments <code>(err, stats)</code> where <code>stats</code> is a <code>fs.Stats</code> object. It looks like this:</p>
<pre><code>{ dev: 2049
, ino: 305352
, mode: 16877
, nlink: 12
, uid: 1000
, gid: 1000
, rdev: 0
, size: 4096
, blksize: 4096
, blocks: 8
, atime: '2009-06-29T11:11:55Z'
, mtime: '2009-06-29T11:11:40Z'
, ctime: '2009-06-29T11:11:40Z'
}
</code></pre>
<p>See the <code>fs.Stats</code> section below for more information.</p>
<h3>fs.statSync(path), fs.lstatSync(path), fs.fstatSync(fd)</h3>
<p>Synchronous stat(2), lstat(2) or fstat(2). Returns an instance of <code>fs.Stats</code>.</p>
<h3>fs.link(srcpath, dstpath, callback)</h3>
<p>Asynchronous link(2). No arguments other than a possible exception are given to the completion callback.</p>
<h3>fs.linkSync(dstpath, srcpath)</h3>
<p>Synchronous link(2).</p>
<h3>fs.symlink(linkdata, path, callback)</h3>
<p>Asynchronous symlink(2). No arguments other than a possible exception are given to the completion callback.</p>
<h3>fs.symlinkSync(linkdata, path)</h3>
<p>Synchronous symlink(2).</p>
<h3>fs.readlink(path, callback)</h3>
<p>Asynchronous readlink(2). The callback gets two arguments <code>(err, resolvedPath)</code>.</p>
<h3>fs.readlinkSync(path)</h3>
<p>Synchronous readlink(2). Returns the resolved path.</p>
<h3>fs.realpath(path, callback)</h3>
<p>Asynchronous realpath(2). The callback gets two arguments <code>(err, resolvedPath)</code>.</p>
<h3>fs.realpathSync(path)</h3>
<p>Synchronous realpath(2). Returns the resolved path.</p>
<h3>fs.unlink(path, callback)</h3>
<p>Asynchronous unlink(2). No arguments other than a possible exception are given to the completion callback.</p>
<h3>fs.unlinkSync(path)</h3>
<p>Synchronous unlink(2).</p>
<h3>fs.rmdir(path, callback)</h3>
<p>Asynchronous rmdir(2). No arguments other than a possible exception are given to the completion callback.</p>
<h3>fs.rmdirSync(path)</h3>
<p>Synchronous rmdir(2).</p>
<h3>fs.mkdir(path, mode, callback)</h3>
<p>Asynchronous mkdir(2). No arguments other than a possible exception are given to the completion callback.</p>
<h3>fs.mkdirSync(path, mode)</h3>
<p>Synchronous mkdir(2).</p>
<h3>fs.readdir(path, callback)</h3>
<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>
<h3>fs.readdirSync(path)</h3>
<p>Synchronous readdir(3). Returns an array of filenames excluding <code>'.'</code> and
<code>'..'</code>.</p>
<h3>fs.close(fd, callback)</h3>
<p>Asynchronous close(2). No arguments other than a possible exception are given to the completion callback.</p>
<h3>fs.closeSync(fd)</h3>
<p>Synchronous close(2).</p>
<h3>fs.open(path, flags, mode, callback)</h3>
<p>Asynchronous file open. See open(2). Flags can be 'r', 'r+', 'w', 'w+', 'a',
or 'a+'. The callback gets two arguments <code>(err, fd)</code>.</p>
<h3>fs.openSync(path, flags, mode)</h3>
<p>Synchronous open(2).</p>
<h3>fs.write(fd, buffer, offset, length, position, callback)</h3>
<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 two arguments <code>(err, written)</code> where <code>written</code>
specifies how many <em>bytes</em> were written.</p>
<h3>fs.writeSync(fd, data, position, encoding)</h3>
<p>Synchronous version of <code>fs.write()</code>. Returns the number of bytes written.</p>
<h3>fs.read(fd, buffer, offset, length, position, callback)</h3>
<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 offset within the buffer where writing will start.</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 two arguments, <code>(err, bytesRead)</code>.</p>
<h3>fs.readSync(fd, buffer, offset, length, position)</h3>
<p>Synchronous version of <code>fs.read</code>. Returns the number of <code>bytesRead</code>.</p>
<h3>fs.readFile(filename, [encoding,] callback)</h3>
<p>Asynchronously reads the entire contents of a file. Example:</p>
<pre><code>fs.readFile('/etc/passwd', function (err, data) {
if (err) throw err;
sys.puts(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>
<h3>fs.readFileSync(filename [, encoding])</h3>
<p>Synchronous version of <code>fs.readFile</code>. Returns the contents of the <code>filename</code>.</p>
<p>If <code>encoding</code> is specified then this function returns a string. Otherwise it
returns a buffer.</p>
<h3>fs.writeFile(filename, data, encoding='utf8', callback)</h3>
<p>Asynchronously writes data to a file. Example:</p>
<pre><code>fs.writeFile('message.txt', 'Hello Node', function (err) {
if (err) throw err;
sys.puts('It\'s saved!');
});
</code></pre>
<h3>fs.writeFileSync(filename, data, encoding='utf8')</h3>
<p>The synchronous version of <code>fs.writeFile</code>.</p>
<h3>fs.watchFile(filename, [options,] listener)</h3>
<p>Watch for changes on <code>filename</code>. The callback <code>listener</code> will be called each
time the file changes.</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>, a polling
value in milliseconds. The default is <code>{persistent: true, interval: 0}</code>.</p>
<p>The <code>listener</code> gets two arguments the current stat object and the previous
stat object:</p>
<pre><code>fs.watchFile(f, function (curr, prev) {
sys.puts('the current mtime is: ' + curr.mtime);
sys.puts('the previous mtime was: ' + prev.mtime);
});
</code></pre>
<p>These stat objects are instances of <code>fs.Stat</code>.</p>
<h3>fs.unwatchFile(filename)</h3>
<p>Stop watching for changes on <code>filename</code>.</p>
<h2 id="fs.Stats">fs.Stats</h2>
<p>Objects returned from <code>fs.stat()</code> and <code>fs.lstat()</code> 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>
<h2 id="fs.ReadStream">fs.ReadStream</h2>
<p><code>ReadStream</code> is a readable stream.</p>
<h3>fs.createReadStream(path, [options])</h3>
<p>Returns a new ReadStream object.</p>
<p><code>options</code> is an object with the following defaults:</p>
<pre><code>{ 'flags': 'r'
, 'encoding': 'binary'
, 'mode': 0666
, 'bufferSize': 4 * 1024
}
</code></pre>
<h3>readStream.readable</h3>
<p>A boolean that is <code>true</code> by default, but turns <code>false</code> after an <code>'error'</code>
occured, the stream came to an <code>'end'</code>, or <code>destroy()</code> was called.</p>
<h3>readStream.pause()</h3>
<p>Stops the stream from reading further data. No <code>'data'</code> event will be fired
until the stream is resumed.</p>
<h3>readStream.resume()</h3>
<p>Resumes the stream. Together with <code>pause()</code> this useful to throttle reading.</p>
<h3>readStream.destroy()</h3>
<p>Allows to close the stream before the <code>'end'</code> is reached. No more events other
than <code>'close'</code> will be fired after this method has been called.</p>
<h2 id="fs.WriteStream">fs.WriteStream</h2>
<p><code>WriteStream</code> is a writable stream.</p>
<h3>fs.createWriteStream(path, [options])</h3>
<p>Returns a new WriteStream object.
<code>options</code> is an object with the following defaults:</p>
<pre><code>{ 'flags': 'w'
, 'encoding': 'binary'
, 'mode': 0666
}
</code></pre>
<h3>writeStream.writeable</h3>
<p>A boolean that is <code>true</code> by default, but turns <code>false</code> after an <code>'error'</code>
occurred or <code>end()</code> / <code>destroy()</code> was called.</p>
<h3>writeStream.write(data, encoding='utf8')</h3>
<p>Returns <code>true</code> if the data was flushed to the kernel, and <code>false</code> if it was
queued up for being written later. A <code>'drain'</code> will fire after all queued data
has been written.</p>
<p>The second optional parameter specifies the encoding of for the string.</p>
<h3>writeStream.end()</h3>
<p>Closes the stream right after all queued <code>write()</code> calls have finished.</p>
<h3>writeStream.destroy()</h3>
<p>Allows to close the stream regardless of its current state.</p>
<h2 id="HTTP">HTTP</h2>
<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'
, 'stream': '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>
<p>HTTPS is supported if OpenSSL is available on the underlying platform.</p>
<h2 id="http.Server">http.Server</h2>
<p>This is an EventEmitter with the following events:</p>
<h3>Event: 'request'</h3>
<p><code>function (request, response) { }</code></p>
<p> <code>request</code> is an instance of <code>http.ServerRequest</code> and <code>response</code> is
an instance of <code>http.ServerResponse</code></p>
<h3>Event: 'connection'</h3>
<p><code>function (stream) { }</code></p>
<p> When a new TCP stream is established. <code>stream</code> is an object of type
<code>net.Stream</code>. Usually users will not want to access this event. The
<code>stream</code> can also be accessed at <code>request.connection</code>.</p>
<h3>Event: 'close'</h3>
<p><code>function (errno) { }</code></p>
<p> Emitted when the server closes.</p>
<h3>http.createServer(requestListener, [options])</h3>
<p>Returns a new web server object.</p>
<p>The <code>options</code> argument is optional. The
<code>options</code> argument accepts the same values as the
options argument for <code>net.Server</code>.</p>
<p>The <code>requestListener</code> is a function which is automatically
added to the <code>'request'</code> event.</p>
<h3>Event: 'request'</h3>
<p><code>function (request, response) {}</code></p>
<p>Emitted each time there is request. Note that there may be multiple requests
per connection (in the case of keep-alive connections).</p>
<h3>Event: 'upgrade'</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'</h3>
<p><code>function (exception) {}</code></p>
<p>If a client connection emits an 'error' event - it will forwarded here.</p>
<h3>server.listen(port, hostname=null, callback=null)</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>This function is asynchronous. The last parameter <code>callback</code> will be called
when the server has been bound to the port.</p>
<h3>server.listen(path, callback=null)</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 called
when the server has been bound.</p>
<h3>server.setSecure(credentials)</h3>
<p>Enables HTTPS support for the server, with the crypto module credentials specifying the private key and certificate of the server, and optionally the CA certificates for use in client authentication.</p>
<p>If the credentials hold one or more CA certificates, then the server will request for the client to submit a client certificate as part of the HTTPS connection handshake. The validity and content of this can be accessed via verifyPeer() and getPeerCertificate() from the server's request.connection.</p>
<h3>server.close()</h3>
<p>Stops the server from accepting new connections.</p>
<h2 id="http.ServerRequest">http.ServerRequest</h2>
<p>This object is created internally by a HTTP server--not by
the user--and passed as the first argument to a <code>'request'</code> listener.</p>
<p>This is an EventEmitter with the following events:</p>
<h3>Event: 'data'</h3>
<p><code>function (chunk) { }</code></p>
<p>Emitted when a piece of the message body is received.</p>
<p>Example: A chunk of the body is given as the single
argument. The transfer-encoding has been decoded. The
body chunk is a string. The body encoding is set with
<code>request.setBodyEncoding()</code>.</p>
<h3>Event: 'end'</h3>
<p><code>function () { }</code></p>
<p>Emitted exactly once for each message. No arguments. After
emitted no other events will be emitted on the request.</p>
<h3>request.method</h3>
<p>The request method as a string. Read only. Example:
<code>'GET'</code>, <code>'DELETE'</code>.</p>
<h3>request.url</h3>
<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>request.headers</h3>
<p>Read only.</p>
<h3>request.httpVersion</h3>
<p>The HTTP protocol version as a string. Read only. Examples:
<code>'1.1'</code>, <code>'1.0'</code>.
Also <code>request.httpVersionMajor</code> is the first integer and
<code>request.httpVersionMinor</code> is the second.</p>
<h3>request.setEncoding(encoding='binary')</h3>
<p>Set the encoding for the request body. Either <code>'utf8'</code> or <code>'binary'</code>. Defaults
to <code>'binary'</code>.</p>
<h3>request.pause()</h3>
<p>Pauses request from emitting events. Useful to throttle back an upload.</p>
<h3>request.resume()</h3>
<p>Resumes a paused request.</p>
<h3>request.connection</h3>
<p>The <code>net.Stream</code> object assocated with the connection.</p>
<p>With HTTPS support, use request.connection.verifyPeer() and
request.connection.getPeerCertificate() to obtain the client's
authentication details.</p>
<h2 id="http.ServerResponse">http.ServerResponse</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. It is a writable stream.</p>
<h3>response.writeHead(statusCode[, reasonPhrase] , headers)</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 <code>response.end()</code> is called.</p>
<h3>response.write(chunk, encoding)</h3>
<p>This method must be called after <code>writeHead</code> was
called. It sends a chunk of the response body. This method may
be called multiple times to provide successive parts of the body.</p>
<p>If <code>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>'ascii'</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>
<h3>response.end()</h3>
<p>This method signals to the server that all of the response headers and body
has been sent; that server should consider this message complete.
The method, <code>response.end()</code>, MUST be called on each
response.</p>
<h2 id="http.Client">http.Client</h2>
<p>An HTTP client is constructed with a server address as its
argument, the returned handle is then used to issue one or more
requests. Depending on the server connected to, the client might
pipeline the requests or reestablish the stream after each
stream. <em>Currently the implementation does not pipeline requests.</em></p>
<p>Example of connecting to <code>google.com</code>:</p>
<pre><code>var sys = require('sys'),
http = require('http');
var google = http.createClient(80, 'www.google.com');
var request = google.request('GET', '/',
{'host': 'www.google.com'});
request.end();
request.addListener('response', function (response) {
sys.puts('STATUS: ' + response.statusCode);
sys.puts('HEADERS: ' + JSON.stringify(response.headers));
response.setEncoding('utf8');
response.addListener('data', function (chunk) {
sys.puts('BODY: ' + chunk);
});
});
</code></pre>
<h3>http.createClient(port, host, secure, credentials)</h3>
<p>Constructs a new HTTP client. <code>port</code> and
<code>host</code> refer to the server to be connected to. A
stream is not established until a request is issued.</p>
<p><code>secure</code> is an optional boolean flag to enable https support and <code>credentials</code> is an optional credentials object from the crypto module, which may hold the client's private key, certificate, and a list of trusted CA certificates.</p>
<p>If the connection is secure, but no explicit CA certificates are passed in the credentials, then node.js will default to the publicly trusted list of CA certificates, as given in http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt</p>
<h3>client.request([method], path, [request_headers])</h3>
<p>Issues a request; if necessary establishes stream. Returns a <code>http.ClientRequest</code> instance.</p>
<p><code>method</code> is optional and defaults to 'GET' if omitted.</p>
<p><code>request_headers</code> is optional.
Additional request headers might be added internally
by Node. Returns a <code>ClientRequest</code> object.</p>
<p>Do remember to include the <code>Content-Length</code> header if you
plan on sending a body. If you plan on streaming the body, perhaps
set <code>Transfer-Encoding: chunked</code>.</p>
<p><em>NOTE</em>: the request is not complete. This method only sends the header of
the request. One needs to call <code>request.end()</code> to finalize the request and
retrieve the response. (This sounds convoluted but it provides a chance for
the user to stream a body to the server with <code>request.write()</code>.)</p>
<h3>client.verifyPeer()</h3>
<p>Returns true or false depending on the validity of the server's certificate in the context of the defined or default list of trusted CA certificates.</p>
<h3>client.getPeerCertificate()</h3>
<p>Returns a JSON structure detailing the server's certificate, containing a dictionary with keys for the certificate 'subject', 'issuer', 'valid_from' and 'valid_to'</p>
<h2 id="http.ClientRequest">http.ClientRequest</h2>
<p>This object is created internally and returned from the <code>request()</code> method
of a <code>http.Client</code>. It represents an <em>in-progress</em> request whose header has
already been sent.</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 <code>http.ClientResponse</code>.</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. Note that
the <code>'response'</code> event is called before any part of the response body is received,
so there is no need to worry about racing to catch the first part of the
body. As long as a listener for <code>'data'</code> is added during the <code>'response'</code>
event, the entire body will be caught.</p>
<pre><code>// Good
request.addListener('response', function (response) {
response.addListener('data', function (chunk) {
sys.puts('BODY: ' + chunk);
});
});
// Bad - misses all or part of the body
request.addListener('response', function (response) {
setTimeout(function () {
response.addListener('data', function (chunk) {
sys.puts('BODY: ' + chunk);
});
}, 10);
});
</code></pre>
<p>This is a writable stream.</p>
<p>This is an <code>EventEmitter</code> with the following events:</p>
<h3>Event 'response'</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 <code>http.ClientResponse</code>.</p>
<h3>request.write(chunk, encoding='ascii')</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 an array of integers
or a string.</p>
<p>The <code>encoding</code> argument is optional and only
applies when <code>chunk</code> is a string. The encoding
argument should be either <code>'utf8'</code> or
<code>'ascii'</code>. By default the body uses ASCII encoding,
as it is faster.</p>
<h3>request.end()</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>
<h2 id="http.ClientResponse">http.ClientResponse</h2>
<p>This object is created when making a request with <code>http.Client</code>. It is
passed to the <code>'response'</code> event of the request object.</p>
<p>The response implements the <strong>readable stream</strong> interface.</p>
<h3>Event: 'data'</h3>
<p><code>function (chunk) {}</code></p>
<p>Emitted when a piece of the message body is received.</p>
<pre><code>Example: A chunk of the body is given as the single
argument. The transfer-encoding has been decoded. The
body chunk a String. The body encoding is set with
`response.setBodyEncoding()`.
</code></pre>
<h3>Event: 'end'</h3>
<p><code>function () {}</code></p>
<p>Emitted exactly once for each message. No arguments. After
emitted no other events will be emitted on the response.</p>
<h3>response.statusCode</h3>
<p>The 3-digit HTTP response status code. E.G. <code>404</code>.</p>
<h3>response.httpVersion</h3>
<p>The HTTP version of the connected-to server. Probably either
<code>'1.1'</code> or <code>'1.0'</code>.
Also <code>response.httpVersionMajor</code> is the first integer and
<code>response.httpVersionMinor</code> is the second.</p>
<h3>response.headers</h3>
<p>The response headers.</p>
<h3>response.setEncoding(encoding)</h3>
<p>Set the encoding for the response body. Either <code>'utf8'</code> or <code>'binary'</code>.
Defaults to <code>'binary'</code>.</p>
<h3>response.pause()</h3>
<p>Pauses response from emitting events. Useful to throttle back a download.</p>
<h3>response.resume()</h3>
<p>Resumes a paused response.</p>
<h3>response.client</h3>
<p>A reference to the <code>http.Client</code> that this response belongs to.</p>
<h2 id="net.Server">net.Server</h2>
<p>This class is used to create a TCP or UNIX server.</p>
<p>Here is an example of a echo server which listens for connections
on port 8124:</p>
<pre><code>var net = require('net');
var server = net.createServer(function (stream) {
stream.setEncoding('utf8');
stream.addListener('connect', function () {
stream.write('hello\r\n');
});
stream.addListener('data', function (data) {
stream.write(data);
});
stream.addListener('end', function () {
stream.write('goodbye\r\n');
stream.end();
});
});
server.listen(8124, 'localhost');
</code></pre>
<p>To listen on the socket <code>'/tmp/echo.sock'</code>, the last line would just be
changed to</p>
<pre><code>server.listen('/tmp/echo.sock');
</code></pre>
<p>This is an EventEmitter with the following events:</p>
<h3>Event: 'connection'</h3>
<p><code>function (stream) {}</code></p>
<p>Emitted when a new connection is made. <code>stream</code> is an instance of
<code>net.Stream</code>.</p>
<h3>Event: 'close'</h3>
<p><code>function () {}</code></p>
<p>Emitted when the server closes.</p>
<h3>net.createServer(connectionListener)</h3>
<p>Creates a new TCP server. The <code>connection_listener</code> argument is
automatically set as a listener for the <code>'connection'</code> event.</p>
<h3>server.listen(port, host=null, callback=null)</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>
<h3>server.listen(path, callback=null)</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 called
when the server has been bound.</p>
<h3>server.close()</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>
<h2 id="net.Stream">net.Stream</h2>
<p>This object is an abstraction of of a TCP or UNIX socket. <code>net.Stream</code>
instance 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>
<p><code>net.Stream</code> instances are an EventEmitters with the following events:</p>
<h3>Event: 'connect'</h3>
<p><code>function () { }</code></p>
<p>Emitted when a stream connection successfully is established.
See <code>connect()</code>.</p>
<h3>Event: 'secure'</h3>
<p><code>function () { }</code></p>
<p>Emitted when a stream connection successfully establishes a HTTPS handshake with its peer.</p>
<h3>Event: 'data'</h3>
<p><code>function (data) { }</code></p>
<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>stream.setEncoding()</code>.
(See the section on Readable Streams for more infromation.)</p>
<h3>Event: 'end'</h3>
<p><code>function () { }</code></p>
<p>Emitted when the other end of the stream sends a FIN packet. After this is
emitted the <code>readyState</code> will be <code>'writeOnly'</code>. One should probably just
call <code>stream.end()</code> when this event is emitted.</p>
<h3>Event: 'timeout'</h3>
<p><code>function () { }</code></p>
<p>Emitted if the stream times out from inactivity. This is only to notify that
the stream has been idle. The user must manually close the connection.</p>
<p>See also: <code>stream.setTimeout()</code></p>
<h3>Event: 'drain'</h3>
<p><code>function () { }</code></p>
<p>Emitted when the write buffer becomes empty. Can be used to throttle uploads.</p>
<h3>Event: 'error'</h3>
<p><code>function (exception) { }</code></p>
<p>Emitted when an error occurs. The <code>'close'</code> event will be called directly
following this event.</p>
<h3>Event: 'close'</h3>
<p><code>function () { }</code></p>
<p>Emitted once the stream is fully closed. The argument <code>had_error</code> is a boolean which says if
the stream was closed due to a transmission
error.</p>
<h3>net.createConnection(port, host='127.0.0.1')</h3>
<p>Construct a new stream object and opens a stream to the specified <code>port</code>
and <code>host</code>. If the second parameter is omitted, localhost is assumed.</p>
<p>When the stream is established the <code>'connect'</code> event will be emitted.</p>
<h3>stream.connect(port, host='127.0.0.1')</h3>
<p>Opens a stream to the specified <code>port</code> and <code>host</code>. <code>createConnection()</code>
also opens a stream; normally this method is not needed. Use this only if
a stream is closed and you want to reuse the object to connect to another
server.</p>
<p>This function is asynchronous. When the <code>'connect'</code> event is emitted the
stream 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>
<h3>stream.remoteAddress</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>
<p>This member is only present in server-side connections.</p>
<h3>stream.readyState</h3>
<p>Either <code>'closed'</code>, <code>'open'</code>, <code>'opening'</code>, <code>'readOnly'</code>, or <code>'writeOnly'</code>.</p>
<h3>stream.setEncoding(encoding)</h3>
<p>Sets the encoding (either <code>'ascii'</code>, <code>'utf8'</code>, or <code>'binary'</code>) for data that is
received.</p>
<h3>stream.setSecure(credentials)</h3>
<p>Enables HTTPS support for the stream, with the crypto module credentials specifying the private key and certificate of the stream, and optionally the CA certificates for use in peer authentication.</p>
<p>If the credentials hold one ore more CA certificates, then the stream will request for the peer to submit a client certificate as part of the HTTPS connection handshake. The validity and content of this can be accessed via verifyPeer() and getPeerCertificate().</p>
<h3>stream.verifyPeer()</h3>
<p>Returns true or false depending on the validity of the peers's certificate in the context of the defined or default list of trusted CA certificates.</p>
<h3>stream.getPeerCertificate()</h3>
<p>Returns a JSON structure detailing the peer's certificate, containing a dictionary with keys for the certificate 'subject', 'issuer', 'valid_from' and 'valid_to'</p>
<h3>stream.write(data, encoding='ascii')</h3>
<p>Sends data on the stream. The second parameter specifies the encoding in
the case of a string--it defaults to ASCII because encoding to UTF8 is rather
slow.</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>stream.end()</h3>
<p>Half-closes the stream. I.E., it sends a FIN packet. It is possible the
server will still send some data. After calling this <code>readyState</code> will be
<code>'readOnly'</code>.</p>
<h3>stream.destroy()</h3>
<p>Ensures that no more I/O activity happens on this stream. Only necessary in
case of errors (parse error or so).</p>
<h3>stream.pause()</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>stream.resume()</h3>
<p>Resumes reading after a call to <code>pause()</code>.</p>
<h3>stream.setTimeout(timeout)</h3>
<p>Sets the stream to timeout after <code>timeout</code> milliseconds of inactivity on
the stream. By default <code>net.Stream</code> do not have a timeout.</p>
<p>When an idle timeout is triggered the stream 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 stream.</p>
<p>If <code>timeout</code> is 0, then the existing idle timeout is disabled.</p>
<h3>stream.setNoDelay(noDelay=true)</h3>
<p>Disables the Nagle algorithm. By default TCP connections use the Nagle
algorithm, they buffer data before sending it off. Setting <code>noDelay</code> will
immediately fire off data each time <code>stream.write()</code> is called.</p>
<h3>stream.setKeepAlive(enable=false, initialDelay)</h3>
<p>Enable/disable keep-alive functionality, and optionally set the initial
delay before the first keepalive probe is sent on an idle stream.
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.</p>
<h2 id="Crypto">Crypto</h2>
<p>Use <code>require('crypto')</code> to access this module.</p>
<p>The crypto module requires OpenSSL to be available on the underlying platform. It 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>
<h3>crypto.createCredentials(details)</h3>
<p>Creates a credentials object, with the optional details being a dictionary with keys:</p>
<p><code>key</code> : a string holding the PEM encoded private key</p>
<p><code>cert</code> : a string holding the PEM encoded certificate</p>
<p><code>ca</code> : either a string or list of strings of PEM encoded CA certificates to trust.</p>
<p>If no 'ca' details are given, then node.js will use the default publicly trusted list of CAs as given in
http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt</p>
<h3>crypto.createHash(algorithm)</h3>
<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 sha1, md5, sha256, sha512, etc. On recent releases, <code>openssl list-message-digest-algorithms</code> will display the available digest algorithms.</p>
<h3>hash.update(data)</h3>
<p>Updates the hash content with the given <code>data</code>. This can be called many times with new data as it is streamed.</p>
<h3>hash.digest(encoding)</h3>
<p>Calculates the digest of all of the passed data to be hashed. The <code>encoding</code> can be 'hex', 'binary' or 'base64'.</p>
<h3>crypto.createHmac(algorithm, key)</h3>
<p>Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key.</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>
<h3>hmac.update(data)</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)</h3>
<p>Calculates the digest of all of the passed data to the hmac. The <code>encoding</code> can be 'hex', 'binary' or 'base64'.</p>
<h3>crypto.createCipher(algorithm, key)</h3>
<p>Creates and returns a cipher object, with the given algorithm and key.</p>
<p><code>algorithm</code> is dependent on OpenSSL, examples are aes192, etc. On recent releases, <code>openssl list-cipher-algorithms</code> will display the available cipher algorithms.</p>
<h3>cipher.update(data, input_encoding, output_encoding)</h3>
<p>Updates the cipher with <code>data</code>, the encoding of which is given in <code>input_encoding</code> and can be 'utf8', 'ascii' or 'binary'. The <code>output_encoding</code> specifies the output format of the enciphered data, and can be 'binary', 'base64' or 'hex'.</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)</h3>
<p>Returns any remaining enciphered contents, with <code>output_encoding</code> as update above.</p>
<h3>crypto.createDecipher(algorithm, key)</h3>
<p>Creates and returns a decipher object, with the given algorithm and key. This is the mirror of the cipher object above.</p>
<h3>decipher.update(data, input_encoding, output_encoding)</h3>
<p>Updates the decipher with <code>data</code>, which is encoded in 'binary', 'base64' or 'hex'. The <code>output_decoding</code> specifies in what format to return the deciphered plaintext - either 'binary', 'ascii' or 'utf8'.</p>
<h3>decipher.final(output_encoding)</h3>
<p>Returns any remaining plaintext which is deciphered, with `output_encoding' as update above.</p>
<h3>crypto.createSign(algorithm)</h3>
<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 'RSA-SHA256'.</p>
<h3>signer.update(data)</h3>
<p>Updates the signer object with data. This can be called many times with new data as it is streamed.</p>
<h3>signer.sign(private_key, output_format)</h3>
<p>Calculates the signature on all the updated data passed through the signer. <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 'binary', 'hex' or 'base64'</p>
<h3>crypto.createVerify(algorithm)</h3>
<p>Creates and returns a verification object, with the given algorithm. This is the mirror of the signing object above.</p>
<h3>verifier.update(data)</h3>
<p>Updates the verifyer object with data. This can be called many times with new data as it is streamed.</p>
<h3>verifier.verify(public_key, signature, signature_format)</h3>
<p>Verifies the signed data by using the <code>public_key</code> which is a string containing the PEM encoded public key, and <code>signature</code>, which is the previously calculates signature for the data, in the <code>signature_format</code> which can be 'binary', 'hex' or 'base64'.</p>
<p>Returns true or false depending on the validity of the signature for the data and public key.</p>
<h2 id="DNS">DNS</h2>
<p>Use <code>require('dns')</code> to access this module.</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'),
sys = require('sys');
dns.resolve4('www.google.com', function (err, addresses) {
if (err) throw err;
sys.puts('addresses: ' + JSON.stringify(addresses));
for (var i = 0; i < addresses.length; i++) {
var a = addresses[i];
dns.reverse(a, function (err, domains) {
if (err) {
sys.puts('reverse for ' + a + ' failed: ' +
err.message);
} else {
sys.puts('reverse for ' + a + ': ' +
JSON.stringify(domains));
}
});
}
});
</code></pre>
<h3>dns.resolve(domain, rrtype = 'A', callback)</h3>
<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), <code>AAAA</code> (IPV6
addresses), <code>MX</code> (mail exchange records), <code>TXT</code> (text records), <code>SRV</code> (SRV
records), and <code>PTR</code> (used for reverse IP lookups).</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> would be an instanceof <code>Error</code> object, where <code>err.errno</code> is
one of the error codes listed below and <code>err.message</code> is a string describing
the error in English.</p>
<h3>dns.resolve4(domain, callback)</h3>
<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.<br />
<code>['74.125.79.104', '74.125.79.105', '74.125.79.106']</code>).</p>
<h3>dns.resolve6(domain, callback)</h3>
<p>The same as <code>dns.resolve4()</code> except for IPv6 queries (an <code>AAAA</code> query).</p>
<h3>dns.resolveMx(domain, callback)</h3>
<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>
<h3>dns.resolveTxt(domain, callback)</h3>
<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>
<h3>dns.resolveSrv(domain, callback)</h3>
<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>
<h3>dns.reverse(ip, callback)</h3>
<p>Reverse resolves an ip address to an array of domain names.</p>
<p>The callback has arguments <code>(err, domains)</code>.</p>
<p>If there an an error, <code>err</code> will be non-null and an instanceof the Error
object.</p>
<p>Each DNS query can return an error code.</p>
<ul>
<li><code>dns.TEMPFAIL</code>: timeout, SERVFAIL or similar.</li>
<li><code>dns.PROTOCOL</code>: got garbled reply.</li>
<li><code>dns.NXDOMAIN</code>: domain does not exists.</li>
<li><code>dns.NODATA</code>: domain exists but no data of reqd type.</li>
<li><code>dns.NOMEM</code>: out of memory while processing.</li>
<li><code>dns.BADQUERY</code>: the query is malformed.</li>
</ul>
<h2 id="Assert">Assert</h2>
<p>This module is used for writing unit tests for your applications, you can
access it with <code>require('assert')</code>.</p>
<h3>assert.fail(actual, expected, message, operator)</h3>
<p>Tests if <code>actual</code> is equal to <code>expected</code> using the operator provided.</p>
<h3>assert.ok(value, message)</h3>
<p>Tests if value is a <code>true</code> value, it is equivalent to <code>assert.equal(true, value, message);</code></p>
<h3>assert.equal(actual, expected, message)</h3>
<p>Tests shallow, coercive equality with the equal comparison operator ( <code>==</code> ).</p>
<h3>assert.notEqual(actual, expected, message)</h3>
<p>Tests shallow, coercive non-equality with the not equal comparison operator ( <code>!=</code> ).</p>
<h3>assert.deepEqual(actual, expected, message)</h3>
<p>Tests for deep equality.</p>
<h3>assert.notDeepEqual(actual, expected, message)</h3>
<p>Tests for any deep inequality.</p>
<h3>assert.strictEqual(actual, expected, message)</h3>
<p>Tests strict equality, as determined by the strict equality operator ( <code>===</code> )</p>
<h3>assert.notStrictEqual(actual, expected, message)</h3>
<p>Tests strict non-equality, as determined by the strict not equal operator ( <code>!==</code> )</p>
<h3>assert.throws(block, error, message)</h3>
<p>Expects <code>block</code> to throw an error.</p>
<h3>assert.doesNotThrow(block, error, message)</h3>
<p>Expects <code>block</code> not to throw an error.</p>
<h3>assert.ifError(value)</h3>
<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>
<h2 id="Path">Path</h2>
<p>This module contains utilities for dealing with file paths. Use
<code>require('path')</code> to use it. It provides the following methods:</p>
<h3>path.join(/<em> path1, path2, ... </em>/)</h3>
<p>Join all arguments together and resolve the resulting path. Example:</p>
<pre><code>node> require('path').join(
... '/foo', 'bar', 'baz/asdf', 'quux', '..')
'/foo/bar/baz/asdf'
</code></pre>
<h3>path.normalizeArray(arr)</h3>
<p>Normalize an array of path parts, taking care of <code>'..'</code> and <code>'.'</code> parts. Example:</p>
<pre><code>path.normalizeArray(['',
'foo', 'bar', 'baz', 'asdf', 'quux', '..'])
// returns
[ '', 'foo', 'bar', 'baz', 'asdf' ]
</code></pre>
<h3>path.normalize(p)</h3>
<p>Normalize a string path, taking care of <code>'..'</code> and <code>'.'</code> parts. Example:</p>
<pre><code>path.normalize('/foo/bar/baz/asdf/quux/..')
// returns
'/foo/bar/baz/asdf'
</code></pre>
<h3>path.dirname(p)</h3>
<p>Return the directory name of a path. Similar to the Unix <code>dirname</code> command. Example:</p>
<pre><code>path.dirname('/foo/bar/baz/asdf/quux')
// returns
'/foo/bar/baz/asdf'
</code></pre>
<h3>path.basename(p, ext)</h3>
<p>Return the last portion of a path. Similar to the Unix <code>basename</code> command. 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>
<h3>path.extname(p)</h3>
<p>Return the extension of the path. Everything after the last '.' in the last portion
of the path. If there is no '.' in the last portion of the path or the only '.' is
the first character, then it returns an empty string. Examples:</p>
<pre><code>path.extname('index.html')
// returns
'.html'
path.extname('index')
// returns
''
</code></pre>
<h3>path.exists(p, callback)</h3>
<p>Test whether or not the given path exists. Then, call the <code>callback</code> argument with either true or false. Example:</p>
<pre><code>path.exists('/etc/passwd', function (exists) {
sys.debug(exists ? "it's there" : "no passwd!");
});
</code></pre>
<h2 id="URL">URL</h2>
<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></p>
<p>The full URL that was originally parsed. Example:
<code>'http://user:pass@host.com:8080/p/a/t/h?query=string#hash'</code></p></li>
<li><p><code>protocol</code></p>
<p>The request protocol. Example: <code>'http:'</code></p></li>
<li><p><code>host</code></p>
<p>The full host portion of the URL, including port and authentication information. Example:
<code>'user:pass@host.com:8080'</code></p></li>
<li><p><code>auth</code></p>
<p>The authentication information portion of a URL. Example: <code>'user:pass'</code></p></li>
<li><p><code>hostname</code></p>
<p>Just the hostname portion of the host. Example: <code>'host.com'</code></p></li>
<li><p><code>port</code></p>
<p>The port number portion of the host. Example: <code>'8080'</code></p></li>
<li><p><code>pathname</code></p>
<p>The path section of the URL, that comes after the host and before the query, including the initial slash if present. Example: <code>'/p/a/t/h'</code></p></li>
<li><p><code>search</code></p>
<p>The 'query string' portion of the URL, including the leading question mark. Example: <code>'?query=string'</code></p></li>
<li><p><code>query</code></p>
<p>Either the 'params' portion of the query string, or a querystring-parsed object. Example:
<code>'query=string'</code> or <code>{'query':'string'}</code></p></li>
<li><p><code>hash</code></p>
<p>The 'fragment' portion of the URL including the pound-sign. Example: <code>'#hash'</code></p></li>
</ul>
<p>The following methods are provided by the URL module:</p>
<h3>url.parse(urlStr, parseQueryString=false)</h3>
<p>Take a URL string, and return an object. Pass <code>true</code> as the second argument to also parse
the query string using the <code>querystring</code> module.</p>
<h3>url.format(urlObj)</h3>
<p>Take a parsed URL object, and return a formatted URL string.</p>
<h3>url.resolve(from, to)</h3>
<p>Take a base URL, and a href URL, and resolve them as a browser would for an anchor tag.</p>
<h2 id="Query String">Query String</h2>
<p>This module provides utilities for dealing with query strings. It provides the following methods:</p>
<h3>querystring.stringify(obj, sep='&', eq='=', munge=true)</h3>
<p>Serialize an object to a query string. Optionally override the default separator and assignment characters.
Example:</p>
<pre><code>querystring.stringify({foo: 'bar'})
// returns
'foo=bar'
querystring.stringify({foo: 'bar', baz: 'bob'}, ';', ':')
// returns
'foo:bar;baz:bob'
</code></pre>
<p>By default, this function will perform PHP/Rails-style parameter mungeing for arrays and objects used as
values within <code>obj</code>.
Example:</p>
<pre><code>querystring.stringify({foo: 'bar', foo: 'baz', foo: 'boz'})
// returns
'foo[]=bar&foo[]=baz&foo[]=boz'
querystring.stringify({foo: {bar: 'baz'}})
// returns
'foo[bar]=baz'
</code></pre>
<p>If you wish to disable the array mungeing (e.g. when generating parameters for a Java servlet), you
can set the <code>munge</code> argument to <code>false</code>.
Example:</p>
<pre><code>querystring.stringify({foo: 'bar', foo: 'baz', foo: 'boz'}, '&', '=', false)
// returns
'foo=bar&foo=baz&foo=boz'
</code></pre>
<p>Note that when <code>munge</code> is <code>false</code>, parameter names with object values will still be munged.</p>
<h3>querystring.parse(str, sep='&', eq='=')</h3>
<p>Deserialize a query string to an object. Optionally override the default separator and assignment characters.</p>
<pre><code>querystring.parse('a=b&b=c')
// returns
{ 'a': 'b'
, 'b': 'c'
}
</code></pre>
<p>This function can parse both munged and unmunged query strings (see <code>stringify</code> for details).</p>
<h3>querystring.escape</h3>
<p>The escape function used by <code>querystring.stringify</code>, provided so that it could be overridden if necessary.</p>
<h3>querystring.unescape</h3>
<p>The unescape function used by <code>querystring.parse</code>, provided so that it could be overridden if necessary.</p>
<h2 id="REPL">REPL</h2>
<p>A Read-Eval-Print-Loop (REPL) is available both as a standalone program and easily
includable in other programs. 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-editting.</p>
<pre><code>mjr:~$ node
Type '.help' for options.
node> a = [ 1, 2, 3];
[ 1, 2, 3 ]
node> a.forEach(function (v) {
... sys.puts(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 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>
<h3>repl.start(prompt, stream)</h3>
<p>Starts a REPL with <code>prompt</code> as the prompt and <code>stream</code> for all I/O. <code>prompt</code>
is optional and defaults to <code>node></code>. <code>stream</code> is optional and defaults to
<code>process.openStdin()</code>.</p>
<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 sys = require("sys"),
net = require("net"),
repl = require("repl");
connections = 0;
repl.start("node via stdin> ");
net.createServer(function (socket) {
connections += 1;
repl.start("node via Unix socket> ", socket);
}).listen("/tmp/node-repl-sock");
net.createServer(function (socket) {
connections += 1;
repl.start("node via TCP socket> ", socket);
}).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>
<h3>REPL Features</h3>
<p>Inside the REPL, Control+D will exit. Multi-line expressions can be input.</p>
<p>The special variable <code>_</code> (underscore) contains the result of the last expression.</p>
<pre><code>node> [ "a", "b", "c" ]
[ 'a', 'b', 'c' ]
node> _.length
3
node> _ += 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>scope</code> object associated with each
<code>REPLServer</code>. For example:</p>
<pre><code>// repl_test.js
var repl = require("repl"),
msg = "message";
repl.start().scope.m = msg;
</code></pre>
<p>Things in the <code>scope</code> object appear as local within the REPL:</p>
<pre><code>mjr:~$ node repl_test.js
node> m
'message'
</code></pre>
<p>There are a few special REPL commands:</p>
<ul>
<li><p><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.</p></li>
<li><p><code>.clear</code> - Resets the <code>scope</code> object to an empty object and clears any multi-line expression.</p></li>
<li><p><code>.exit</code> - Close the I/O stream, which will cause the REPL to exit.</p></li>
<li><p><code>.help</code> - Show this list of special commands.</p></li>
</ul>
<h2 id="Modules">Modules</h2>
<p>Node uses the CommonJS module system.</p>
<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'),
sys = require('sys');
sys.puts( '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 = 3.14;
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 export an object, add to the special <code>exports</code>
object. (Alternatively, one can use <code>this</code> instead of <code>exports</code>.) Variables
local to the module will be private. In this example the variable <code>PI</code> is
private to <code>circle.js</code>. The function <code>puts()</code> comes from the module <code>'sys'</code>,
which is a built-in module. Modules which are not prefixed by <code>'./'</code> are
built-in module--more about this later.</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 the leading <code>'./'</code>, like <code>require('assert')</code> the module is searched
for in the <code>require.paths</code> array. <code>require.paths</code> on my system looks like
this:</p>
<p><code>[ '/home/ryan/.node_libraries' ]</code></p>
<p>That is, when <code>require('assert')</code> is called Node looks for:</p>
<ul>
<li>1: <code>/home/ryan/.node_libraries/assert.js</code></li>
<li>2: <code>/home/ryan/.node_libraries/assert.node</code></li>
<li>3: <code>/home/ryan/.node_libraries/assert/index.js</code></li>
<li>4: <code>/home/ryan/.node_libraries/assert/index.node</code></li>
</ul>
<p>interrupting once a file is found. Files ending in <code>'.node'</code> are binary Addon
Modules; see 'Addons' below. <code>'index.js'</code> allows one to package a module as
a directory.</p>
<p><code>require.paths</code> can be modified at runtime by simply unshifting new
paths onto it, or at startup with the <code>NODE_PATH</code> environmental
variable (which should be a list of paths, colon separated).</p>
<h2 id="Addons">Addons</h2>
<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).</p></li>
<li><p>libev, 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
received one will need to interface with libev. That is, if you perform
any I/O, libev will need to be used. Node uses the <code>EV_DEFAULT</code> event
loop. Documentation can be found http:/cvs.schmorp.de/libev/ev.html[here].</p></li>
<li><p>libeio, C thread pool library. Used to execute blocking POSIX system
calls asynchronously. Mostly wrappers already exist for such calls, in
<code>src/file.cc</code> so you will probably not need to use it. If you do need it,
look at the header file <code>deps/libeio/eio.h</code>.</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>To get started let's make a small Addon which does the following except in
C++:</p>
<pre><code>exports.hello = 'world';
</code></pre>
<p>To get started we create a file <code>hello.cc</code>:</p>
<pre><code>#include <v8.h>
using namespace v8;
extern 'C' void
init (Handle<Object> target)
{
HandleScope scope;
target->Set(String::New("hello"), String::New("World"));
}
</code></pre>
<p>This source code needs to be built into <code>hello.node</code>, the binary Addon. To
do this we create a file called <code>wscript</code> which is python code and looks
like this:</p>
<pre><code>srcdir = '.'
blddir = 'build'
VERSION = '0.0.1'
def set_options(opt):
opt.tool_options('compiler_cxx')
def configure(conf):
conf.check_tool('compiler_cxx')
conf.check_tool('node_addon')
def build(bld):
obj = bld.new_task_gen('cxx', 'shlib', 'node_addon')
obj.target = 'hello'
obj.source = 'hello.cc'
</code></pre>
<p>Running <code>node-waf configure build</code> will create a file
<code>build/default/hello.node</code> which is our Addon.</p>
<p><code>node-waf</code> is just http://code.google.com/p/waf/[WAF], the python-based build system. <code>node-waf</code> is
provided for the ease of users.</p>
<p>All Node addons must export a function called <code>init</code> with this signature:</p>
<pre><code>extern 'C' void init (Handle<Object> target)
</code></pre>
<p>For the moment, that is all the documentation on addons. Please see
<a href="http://github.com/ry/node_postgres">http://github.com/ry/node_postgres</a> for a real example.</p>
</div>
</div>
<script type="text/javascript" src="./jquery.js"></script>
<script type="text/javascript" src="./sh_main.js"></script>
<script type="text/javascript" src="./sh_javascript.min.js"></script>
<script type="text/javascript" src="./doc.js"></script>
</body>
</html>
|