diff --git a/assets/highlight.css b/assets/highlight.css index 12a0168..34f4edd 100644 --- a/assets/highlight.css +++ b/assets/highlight.css @@ -19,10 +19,14 @@ --dark-hl-8: #4EC9B0; --light-hl-9: #098658; --dark-hl-9: #B5CEA8; - --light-hl-10: #000000; - --dark-hl-10: #C8C8C8; + --light-hl-10: #EE0000; + --dark-hl-10: #D7BA7D; --light-hl-11: #000000FF; --dark-hl-11: #D4D4D4; + --light-hl-12: #811F3F; + --dark-hl-12: #D16969; + --light-hl-13: #000000; + --dark-hl-13: #C8C8C8; --light-code-background: #FFFFFF; --dark-code-background: #1E1E1E; } @@ -40,6 +44,8 @@ --hl-9: var(--light-hl-9); --hl-10: var(--light-hl-10); --hl-11: var(--light-hl-11); + --hl-12: var(--light-hl-12); + --hl-13: var(--light-hl-13); --code-background: var(--light-code-background); } } @@ -56,6 +62,8 @@ --hl-9: var(--dark-hl-9); --hl-10: var(--dark-hl-10); --hl-11: var(--dark-hl-11); + --hl-12: var(--dark-hl-12); + --hl-13: var(--dark-hl-13); --code-background: var(--dark-code-background); } } @@ -72,6 +80,8 @@ --hl-9: var(--light-hl-9); --hl-10: var(--light-hl-10); --hl-11: var(--light-hl-11); + --hl-12: var(--light-hl-12); + --hl-13: var(--light-hl-13); --code-background: var(--light-code-background); } @@ -88,6 +98,8 @@ --hl-9: var(--dark-hl-9); --hl-10: var(--dark-hl-10); --hl-11: var(--dark-hl-11); + --hl-12: var(--dark-hl-12); + --hl-13: var(--dark-hl-13); --code-background: var(--dark-code-background); } @@ -103,4 +115,6 @@ .hl-9 { color: var(--hl-9); } .hl-10 { color: var(--hl-10); } .hl-11 { color: var(--hl-11); } +.hl-12 { color: var(--hl-12); } +.hl-13 { color: var(--hl-13); } pre, code { background: var(--code-background); } diff --git a/assets/navigation.js b/assets/navigation.js index 05bf885..a4eb284 100644 --- a/assets/navigation.js +++ b/assets/navigation.js @@ -1 +1 @@ -window.navigationData = "data:application/octet-stream;base64,H4sIAAAAAAAAA7VabW/bNhD+L9rXpEvcJGuDYUBqO0NRew7sYEVRBAYtnRUiMqlRVJBs6H8f9GKbkijyRKZf7eee544vx+NR3/8LJLzI4DrYklBy8RqcBCmRj8F1sONRnkD2a/3Hu0e5S4KT4ImyKLgenQThI00iASy4/n4g2eQ0iSaQScqIpJwteZJQFt/SBI7E25yFxZ9HaoNZU/bq4sdJr9hQlYH0KymA7IYIVBaDJCKey2EShcUwCRBioAQIYZOY8TgGO28FM5DdLaf399/Ws+nf09nqSPdMBCUbdTk2gE3C96M+wvXqfokmLcB24vFitlhiiY9gLDGa1E74ebX4cHV2jmCskQbKVICUr4tUZrftvNGd+Q7YMP8VdsxZxtXd3HW1AbR62swNfWzdjNCgKv5WNsaRT76mClcL1kqcZx9/O79UWassgeDtAG3Mv1MmQTCS/NGf1dd7zBqV4D/l2y2IKQt5RFnc56lC2jTQenwShAnJsoIli05pdgovlXWgxPJVUFlMWTsLl0pbEurVm1Yt9csrlPKYJ1wgIi1x7gGW5iAlYGM7GLiFNePxBLJQ0FSiwmvg3cO82+eCIkOssbE2rdwCLjnolgIm2iPYM9SSY/oiBckGyVYm7uIzeIbEwQOtnbsbc8gyEsMtFzsib3MWIlzo2LjLG8o384KzVHHYNTcn4mkJ/+RUQISJXIG7B13OWSgRejXSXao46updeUdEhgqyY6M/xh5+PChClEXw0j3Fyp9RB1daSM14XCvrypWKrAU0lCqlTH/dW9EpIANVUgLuIZO6IqViOmIMJUoFmsAmj21MJchKdZOm/cEdINbQbtK0vtQh2GqkgXTG4zJRtZdbRbT/11YfzRZ/Gi4aNdcBYxgq3bpS8svBK+2aGl1eqQs9wyxSFWUeprh73B3c6axJzRDVQ1klwSmTaqWvG3MFiOCeEEl6+Yo/bRxFMkGNfhNomoHZfhm2z0zdjKpIE6mpFK/IBhbiN9krC5eQ8VyEYA9fYddZup1uDaajeGlpVW5Kno8+4M62Z2ByuqNSghgUtcbQLej1XzyCku2eiBgkTr5t5ag9WcyHSzeN3JRXkkgaOo9+r7mbNyoRYt2pcP9lh9jAKvy01Ua56BfU73R/7V9aFLUj5x8v3p8Z3FF3+oaL8iI9fLOdnr87WPvP9hK2IICFlMU92WeAXxhif5fdM7XB3bdL4r2sAzeWycEhm+6h7ducpPoSoe3InKTuN5kJbEmeSLRiC+8ufMNel426v0ewxnkIibjTAOiqiNjjtv8FeqpDReEL6AtDrMAIozDyaJzQTALrq5rVTkkN9Gj5kSRZ0Z6OX0dvj3bsYuaZ5LuyRDfdClS9toV7oAs2Lg62IoINCZ+s0i28u7CAiIRyUNJtmDi3VuNuy80kqlq4aX4iZdeiMbEmxSPeUY+yoqFvzyh7oGcr074de2/8eJGFWEmhedfQi+3RnqJfqXxc0QSY/Qxo4d9MeFjcXTt3R1YgKEnovyBuO+9e3VuEAvaMffxIWFxdyPAJv8fQwxVcJvZNv7guuKbEeZMeuLZ1ZL4s9rWQsPm3mKg5SdPGkjbmX8XCOeerK9iS7DvrF3uKH7vJgw61rp3HyOI2Svve+9P2hY/Q241nx4uftG5cdXx2oavmVAguitNiTPIMdZ9sGLi1aj5LEERy8Y1CEi0hyxNkn0xj6Bb2nmgJMhfMxQXV0teHpnrPTmrCPe6Yxa1/TzagHb038ehDlxSbBFzVFVPX7wv4jmYwo0/IC51i4KbY97LcUfJ/U76jiGtbAXKXWELIBSaWAubzOh4meQRWnRrncendUfvGK0A+s8J48Vg66OxqGZlerQZzI3mVTwBwvIqBjff4yLeSgmMLQJ0lXkn/7YNFxPTxg+5pGSmCEyi+rnj4H2oYd/X9LQAA" \ No newline at end of file +window.navigationData = "data:application/octet-stream;base64,H4sIAAAAAAAAA8Vda5PbthX9L8pXO/E6tht7Op1Za7XJ1lpLlTZ2M4lHA1FYLbIUyYKQs0qn/70Dig+8CF5ccNpP8WTvOefidfG6hH7990TQJzF5N7knicj5afJsUhDxMHk3OeS7Y0rL7+o/fPsgDunk2eSRZbvJu5fPJskDS3ecZpN3v7Yk2yNLd1e0FCwjguXZKk9Tlu2vWUo74vtjlsg/dtQemC775tV/nvWKhaoE0q8Fp+QQInBGBEns8qMIk5CIMAnKeaAE5XxIYp7v93SY92zmISs4FeK0KER5bXZIm9IyBhFP86zMUxrEr2M8MsvV7O7ul81iebfeTBcf14v5rFP4SjgjW3VQOcx18u9fuiuHBRZAAQC9v76Buy5tPX5LcaVHdaziVCiMhpkRcV68/cvFa5X1PLwAvJbhEHNdtOlivlitN+u7FaAeOmNPRWi2YNJhwpv14oc3Ly4AjLWlh/KvLBOUZyT9W/9csGlsNqBp4X2abxdF1TU7zoriniRuWgViSLx+82ySpKQsZTuXu+esfE6fzrCJUgxJ0IlVgH4lXeLi5Q8wieP9PeWzLMl3LNv39T5VSgM4eyFI+DMTDzeHImUJE9Oc8sTT+RV5FwzvxLkwMjAKfpRa4KY1gcgGrmh8Xd7SNHs9SgdSuOcXuDJ9oKfF9neaiLtTQQEtqtnjm/IDPc2eipyLwEFq4nCF/vsfj1gHHFCkD2WefabbD/QElm4ROMXL8nQ4UMFZ8oGerqggLAUX24WN7HCgUNlaI+Mlywg/zdkjpGt3xlH9Gj6QoofQdc4PRMDEzrZ4uX++fvF2+kCTx8ABY+JwvaZioVywe5YQQUF9x8DgelBwg1qBOKxJfy7JHqhWmUaJXab7nDPxcAgIvy0G15BTfipEHhD1WgBO744dKHD8N6b4Kj2Hqma1FThQnGBcoRcFzW7zHaTQjSm+0EChOJG1IKJ8T0oKrc0WgKvBCg6KMpUlLrasKNmZZzwepc4cJ/eZM0ED9BT7CMFPK1oeUwFtNxWDazpZTYGiCgS5M2D7m0wYnWZg2d5B8F00MMQoEJzmdUr2l9nOji9+XQOG1GYplQ0V1rQ6Kk45sLYNGHa+pETQbugH+tADj/FFCQsoZ2w8fpzL3fdnukV504fH95GfSLZL4YOiReAUZ5xn+ewpoYV+EulX1VFxNW/OJbD6ds0oUGXZd8KVdRS+zM4JdLjQvfMoeA17KujuknNygqxiW2P8aquCn8+VPjH6B0DVQOClr1gCju3SFn0IEbDlwWncNLSgxVZrjVtqTfNDkVKhnhr2tlVrG9FBylOWhGjqALxwS2GuAoZL61wBBEjLoTxnGUVMMwoMOfMeeZnzZQ6fahsAUi8/FHlJr7Ml4Wqw89ZyB8BXcsMIGjPNv3BDxpby3Dk1/zJPd171S7kvpszpA675TQutpS/evvr+hccB6+LS6rnB4h1DuA/N/B/jhc0R7kc1VcU4YRDgayKqClDKzUoopvg2B96PKAdQylfHIqVPgTFc8UDD44LrmSIowrXCuFB3x0lW3uf8MCVpuiXJIyCiK9IWHB/fWyp8C5gUyDV1wxLaDi0Q1xRLUpZ3Dzw/7h9ClRUoTpvsdpfbnIs122vznp3F43ZAx5tJPSAX9lRc0XtyTMVPbP/wmQjKbwl/DPelhwjlVDmWUz1EKKeuWcbKBxp66KR4YzDgxsl9TRJeGQ0SVXpbFjZBNLjoddpmU/D8wEp2f9ps8IV/fvGtxhRQGV/UqMEKmrKMrvMjT+h17URYFHdz4EO5zhfjS7wPjmge4kZPTI/yJKZaDJJ4r5RMxBtBuVw9xXUiD+Go3i6roTOeswbfqL5GOxfvDW59Z6Lj/airGedGDY73Aj91Ggy4qbOoScJnjwaJmjptWdjU2eD+31On4sdYUyeyB+CanZUzznOOWTK1UFTDs9I+WIArN1hcnzsPWWWoeXNj1daukahE2STPyuOBcoRuCw0QVrtVQB5FTAoF6mZzxMtV5J1qlLb7gM4vrGLiSgxOxbEHS0heDKJyDVjcDSo4AwhfzN8mWb6j78qqN37XDrjfJqCZaSPBmzN404I3kXPT1kit98bHPhe2jtR+YKCs/hOnLilQ2qS7o410QWFCebLVvpTBtYH1DQ1Q+/dSXamjtCUFcjWij4lm8sMMiQYbOyICD3h6fIg67AlcKPe4gFg0f3HE/ybmLQkDf4LjwmKT+mSp5OITNecrwDFSe36kGeUskf8T/j2Sh2IMn+oD1iplk6RHGp7pOcQ1spdXeTaWkx3VGD5O80zwPE1BCRx90Lh8CmcpwakdAwzxrr0/CavA9hELrDF9XLjW/DnbUZ6eWLZfs+yxupkJdc5DMYZP0zQvHWdSIT5pFGP4tBYktp40ijF8qjIE43zSKKJ9qo6dpyRLaBrhloNlHM+WxzTaL5VjHK9ie5ZNEutXFXOMewioOx12nNrBVsgY4ws3pMaYY6vzPOyU4aAYN2Hbe1img8xTYeAJ3Rip4s9fjrwiA3/D72EYoTZ6PEKuDfFPAPhWKIEV5aKIqim/T/iVV2xdadWPrq4elvH6Fr7Semiw9db34Ya3mnQQMgKN8ckINgLpLHVlVis1aE/xMIxQGz0ehVSNRjFO78COqgGW8eorfFQN0GDr7R9HepSLFcGJoHvwJy0GbBTtNfsTvMRzQJGfKbhehPBr9z4IAdVcUsoRugYMeTr40+Vqtpl9/AQcEa09qu+fs5Aon7NS3AgKya0yIRGvCtBSPm+xzDnsoRjFHnkpl/NHykOv5FQQdkVRVvucOTsw+NfjOgrZk5un+qTzG3BH1lDI5Gt2oNeQfKmzYUQvYk8sAynVlpFSt5TvaRPX4LoGDO9ENQ2DdGvLyEx++QrWHeF7GvoSgRsdkcovud6TMvTaxIWN9GLNsn3w3b4bHekJMg+uDx/pze0xFQzrigrG+XF+BzZQXwOhdWdfaQa+/Gnskd8W9b8e7JcdeET4f1fL2LWw/NBiRf91ZFrmXX/cVczxQbDKfQ54iLKxR35RXmdaB6lZ6TuhaqgyKjjkUveB8Podg6BnNy0caunrUR+4hjeB2O5sESGePfVxIFPz5Gf81ZV+SI/QUWMo298DhHjQk/0f4knoUNRAEWmR+lN2A5oNAKc3exKcJJB7+NoSH0aVLgp8q89AjCKtP3UCqNsOhh3l8g2get5bEl6CZi4L4yy8lgGf5T3zcq+IhXGLfNFSqFi2U79rbjLZqv9t4N25aKyc5/aziV0y2JlJtTKTvdSsMlk5ED7D0ENZ+dz/uwNnOsXIQ5VWBne0FK6J7czU2ZiTmEV0RbfH/RBTZTRIdVkU/YVrTQaLdlkU9Y9qANhqSw/pPN/P6Veamn33TNT8dWgozBc/buazT7O58yn8mqu18VSVq18pEaP1qm/rYC2Ze8tldSNHqerS1/fFmeDWQ1F6NSmGAO4rIkgvn/zjEIeMWKAK0w2HK+2yKKq5Z6ARVEsfqXa0VZl7eG1jH7XvJw7OfErwhYTKakHRnAIO16y5FDGQESuhhsk+pfUr405pq63x7MCE8O8yLW0HEFfozcd8Ryu289EVTN5EIbWvFrfh0joIm5dMBEvQtd8LRy5NFSJAv1PN47sdYACr5tGfU8Zrf2NQ1I6EvJkkM0N79ztDPrTo+NZe0XvKaZawbN8TfQL8ghDHu4yP1B53xwvivayBA8vnYMig+2L6dksK9+rDdOSWFM6VCPDgtLqTBysa9hEb0Oy00nYBPYK1XcxOd2/t/GwVvndv9UAS2rOaPQr2e5phAi8hCma+ToCEvLqWB0WDMo0hXkomda5ZTw6BpddYI1Ml8jQfLlNlFVEgCacCXKLGHH3XcEXLhLNCAIqmWeOLWC372T0DdJDOdAw5c6MzKOrc74QMBLlTDNZ3oqLTQM4/XiPPbQcdsBAR3flYivxQlci3SVd7tInAiy+yqVwM9r3oYkkb9nhhTnck8d7nW9oaJObicHA3b90a9uzqQZryzt9sWJ9iZ4/UY5n8aZfhQdQYRg5e2GCNFFnwteCOHyN0izXWkaLydwXXLNWu1X2ynf1owmHltnF4R9aUM5KyPym3M33snbdiHFn26QPJ9udDDPgiqQcY4QosEseGX1gihWNbMEoahfMk13/A0neiC42/sqFuSVFoXdobfxUEOuZfu69wXc1p9V/oyre7jwma1GxcRM3CBkrMb8cFjYsYofHqE3trGtpv0DkYEaMQq1l97Sdniyk5lqAzGA2AO95sUnV+YTT1/b6SJe4ARiQbiZyvqDjyDOOCioz1wfX+gEc47rGBLjWkL6XGfZESl1+lJaRg1aOzvOqnHnuzWhzb2xaATbd3pwhaSvHJgUsG2LZJI7zEiiY5h5RFmuFlZk9JerR/5dGORWe7iE3vgQ0PPGkU0ypZLtMNguYuA+S76Q3mBvIqaT8wXgUwxNvdua8Fz6ELQBcSruTOdxoQgSU8BYvABGSy05f/AkpQJLe/hgAA" \ No newline at end of file diff --git a/assets/search.js b/assets/search.js index d73b600..adf09b2 100644 --- a/assets/search.js +++ b/assets/search.js @@ -1 +1 @@ -window.searchData = "data:application/octet-stream;base64,H4sIAAAAAAAAA71abWvbSBD+L9uvqut9k184Do42PQqBlCYUDhOMam8ccYrkk5Tc9UL++7GSbM1Is7Ikm/tUGj8zz+w8M7OrlV5ZmvydseXqlf0Zxlu2FB6LgyfDliyMt+Yf5rHnNGJL9pRsnyOTfSj+OnnMnyLmsU0UZJnJ2JKxN6/t4SHY5En6s+Wj+nu3F+0f/XwOI3Od7G72eZjE2dFdGOcmfQg2x6gwjnDvsX2Qmjg/rq7m41OhjoSReTHRIJ53B5MOtoadi3wf5I/DuCuLmjrPtu/D7H0YP5o0zM12bChZ+K8ZFkplcflQHlLz17OJNz+HxQPNLh9UHj6ZLA+e9sOCgmYXCUpMFzOu68a7TnY7kx6Dyn/uj/GUPw3rDcL9tS332zw1wdNVnIMeb3A1cQOJwRDoMwD+j+Yf0/g9yjuMOjqtVdUl+jzKTRJnyRDW2mAwMVFBn4I8cFWN/e0yJdpZl2cV486kv+33V//kadBdkRB4RlnuU5PnHdOPYnp3NDqhGFqMI4CtyfIwDk63YDuMhum4YHzQogfQMY6H53hTuK/COCKGZZzi+JZEURjvTlNVwGGMUjQYP5kfzzXZS5CGwY/64AUwZ/LcmSw/QWMho1mub35fX199v7q+dbLUkNEqbR7DaNvY7poCAcxonn2QZtQZtMnVwI3mC7MeZBA0WqdyRHxsbAa1VIfDOsJ1sx3O/R18n8MeZBZ0BtPXb1d3d3+sP95c33yjivBAhnCX4lvf3n3ry2mx5/M6m63B2afj+vP1W2eNPZ/3y+3N3J/y06QVcCij39xzb/Z59rnxKFu3Ii5ZgD2D98dzGG0/1ZtmeYDuIKcNLhrBNnnOB0VgDS4bgUmpId8RgUlPTPxBEaCZdZp/zPTqYK9OFwODAFbnxuLcZRF3n322zdU8vtt4wSoap/gDYQN1LmnZNKdpW7jBxEfKX4rzcxxEvzou2tYHwHr8w4pN08lHZ0AE8D1IJ2ANo260OpjbN1td9NB83I1WVygjbraGhdbjhqsrvrE3XcOC7HHj1RXk2Juvk0ESz/8V6Ks9kW/JewAQaRM/uvBh430N48QO4CHN17C5TAP2rnqKvV35nfo0F32Raifjoit+ZHBQt6GaXVyvYV3WSgzdZZ2JcSSF2JaHdhZlc5Huwo5v8zQBlzSnplLT8DK6nbg67hNDr/vkxjhsZeES+zAd3fANuW9wg3ZmOrjzt+i+wQ7fq+mIL7Rp9w17+O5Nh32hbbwj7F5H5MOBvO8hud9zR9d0IxhbJr1iQMPk3qvO78tX9mLSzD56LJmYyMmCeewhNNHWvqIvg/TYJnl6ss7uq9++G+vSIkrIhynzVlNPzib+fHF/760OFsUPxR8KGGfeilMwjmCCeStBwQSCSeatpCcWE8F9BJMIppi3UhRMIZhm3kp7wp/MphLBNIL5zFv5FMxHsBnzVjMKNkOwOfNWc2qlcwRbMG+1oGALnF6bbU7qwBtCcFfuOJaC25RzWjOsBrdZ56RsHAvCbeK5JJFYE25zzxWJxLJwm36uSSRWhlsFuE8isTjcisBnJBLrw60OfO5pf6KlwkgskSgkWlBIgSUSVghBiika7VL0C6mRwBoJK4SgWwtrJKwQQpJxYo2EFUIoEok1ElYIoUkk1khYIQSpkcAaCSuEIDUSWCNhhRBkswmskbRCCLLfJNZIFm1EaiSxRtIKIUmNZGOqFWON1EhijaQVQpIaSayRtEJIUiOJNZJWCElqJLFG0gohfRKJNZJWCDkjkVgjaYWQZB9JrJGyQkiyjxTWSFkhFKmRwhopK4QiNVJYI2WFUMKTYqLnHCMbm0+x+5CzTmGNlHbuU1gi5bt2KoUVUjPXXqWwQGru2q0U1kdZERQ5jxXWR1sRFDmPNdZHc+fGi+XRwrUcjdXRhTrk9NBYHa1cC9eNw0EhDjlmNFZHWw0UOWY0lkfPXHuwxvLouasyNJZHL5ypxOr4U+cpBovjc1eCfCyOL5wd4WN1/EIdcrr6pTrF4fTFpLnZfikPqatV+UIAfNVRfpD0ytbVOVbODkfqVybnbPn69lafW+3/LFHTSVq+q2j5mgNfi56+suptEXDjAzez/m6K117AjQZu/N5uyvd3wI0CbnSXm6h67QJsF7Wtmjpsi48e2rZC1rZCuWwPHwPUdlzUdlw67PBnPsAYVAN3VcPxY2FgB8xcVo1i4dBGdBht4Wue2l5NQW67SKNkl+xbKwVZ6iKvjffVUyaIACRLuyoDO8mquy/gBPSMdlWpdUKsQYESUa4SAbbEEkCB+q5iAVcftSXo0SJqj6lZ+a8W5b++q+Crz9VrX0BJt035DI6CBxoqWZG6xAwzRx2AKSFc+a9u+kBjg5lQEnNerd41sKJkty78YHpYhy4BomS3Lb7BBN0DIuAu6dtDBRSbq7tLo8B+sQfogCF3Tfajpak+tQT2IMvcmeWDfXr4jg84AIUqXEVSOtiWn+WBHIP6Eq5JUdrmxad2wBQMKeEqrSjZtQqEg12Du2bDwbDcdEz5dXbtAyy5I+VETXOwYN6RLPdYANErF3dh5mgqYC9cqy8vqAEp4Kwmiq56ylWr+zBObLFQsxFUnHbl4PDRLUgdmGvc1cql2XqTRPYyD64btIlw5g1ar7Mc7/pAdNkd9jrMkvLzKjCXwDiRrnFSmbeHkQR1I12Ngqyb4UvQL9LVL6UH4ugiQPJFd/KbpwkB9mLhLJfCNNnnGXGEkXCmuyaqq9hA4NqV9vKdR20EC7Sq92on1Ye9xFVC5cBwHYyABsqlAXgvUFuCHFZ7uZpXkVQd6ZNVce+xfbg3URgbtlzdv739B61K3RysNgAA"; \ No newline at end of file +window.searchData = "data:application/octet-stream;base64,H4sIAAAAAAAAA71bbW+cSBL+L52v7Oz0G/Oi00mnxDlFsnai2FrpNLJGZGg7aDHMAU42a/m/rxqYoQqqGZhB+ymKXVXP0/VUVTcNfmVZ+iNn6+0r+yNKQrYWHkuCZ8PWLEpC8yfz2EsWszV7TsOX2OS/lj+dfSueY+axfRzkucnZmrE3rxvhMdgXafazE6P+eX8U7Z/ifIxic5s+bQ5FlCb5KVyUFCZ7DPYnVtiOCO+xQ5CZpDitrsHjc6FOgLH5buJROO+OLj1oLT8X+CEovo3Drj0a6CIPf4nyX6Lkm8miwoSXUsmjv8w4KrXH9FQeM/P/F5Psf47jA92mJ1VEzyYvgufDOFLQbRJSYr5acN003m369GSyE6ni5+HEp/rVuN4gwt/acr8rMhM83yQF6PEWVttuJDAYAkMGwD/R/Jc0/oDyjuKeTutUdWV9HeQ+TfJ0DGrjMBqYqKAPQRG4qsb+bpoS7a3Lq4rxyWT/ORxu/iyyoL8ioeEVZXnITFH0TD8K6d3J6YxiaDEOAqHJiygJzrdgl0bLdQIyhyhJx+aicrkMHIr/uUxqXeSlpZtJ1/aKEshMGOyL9z/C0XjvoGtfBoi1NWR8MCSPmTpReXxJ9qVXzeRkMW7BFMaXNI6j5Ok8VG04DlGKFuIH8/WlAfseZFHwtTn6Apsrce5NXpyBsSYXo9xu/ru7vfn95vbOidKYXKzS/lsUh60DR1sgYHMxziHIcuopoI3VsrsYL8oHgEGji3X6/OXm/v5/u83n+7vd+81vd5vbG0Kw40MTYd2PfHwKO4v98dNgYGt6Per7ze3mC1WcLcjKbiq83d39l6GY1vZ63E93m6U/5+dBa8OxiH77lLA5FPnH1sN3U7pH0I7tNLhRbEZhN/aT4L+vTqljKGCXK1h8fYni8ENz2KkefHo40A6TMgjTl2IUA+swLQOTUVtDDwOTndknRjH4CJ+tzuNb8wnR6zPJSBLA61ouzr0ZYQ/ZnbtY7ccuyxesovX0dQRsWV0LWjXNediO3WjgE+S/yoN3EsT/dlyQ7o4Gu8sfMm2azl55ACBgPwB0BtZw0U1kD3L3RrIPHrpfdhPZR+WCG8lx1AbcTPbxu/SGchzJATeVfSQvvbE8S5K4t6mNPttzfNhq5Q7Ttv3FhY8e8KMktQN4TPO1fKZpwMFVT6F3K79Xn/aiJ6l2khdd8ReSg7qN1WxyvcZ1WScxdJf1JsaRFGJbHttZlM8k3YUD3xVZCq52zk2ltuM0up258h/CYdB7gNY47GRhin2YZjd+Qx5KbtTOTJO7foseSnb8Xk0znmjTHkp7/O5N055oG++hPeiIfDyQDz0kn38EsPtD9QTTnv/4EaC1NSGXQRwc442Yt33DlqDTcRlP58GrHyfWr+y7yXL7JLRmYiZnK+axx8jEof3SoyLpsX36/GyDPdS/+93YkNaiMvl1zrzt3JPLmVj6Dw/e9uhR/qL8QWnGmbfllBlHZoJ5W0GZCWQmmbeVnljNllwiM4nMFPO2ijJTyEwzb6s9sZhhI42MfOZt/a6Rj4wWzNsuukYLZLRk3nZJrXGJzFbM264osxVOrM0zJxXgLQm4K2sci8BtsjmtFtaB23xzUjCOpeA25VySllgNbvPOFWmJJeE2+VyTllgXbhXgPmmJxeFWBL4gLbE+3OrASSE5lkiUEpFaCiyRsEIIUkzRapSyU7inFzOFxRRYImF1EIIyxAoJK4MgFRJYIWFlEKRCAiskrAyCVEhghYSVQfgUTSyQsCqIBWWI9RFWBLGkDLE80mogSHkklkeWHUTKI7E80oogyRaSrVFWzjKyhSQWSFoVJCmQxAJJq4JUxNIl1kdaEaSmDLE80oogKXkklkdaESQlj8TySCuCpOSRWB5lNZArwlBhdZSVQM0pQyyOsgooqncU1kZZARTVO6q10ZQ7DSmNwtIoK4Aie0dhbZRVQGlPyhlfLLElFkdZCRQ53RRWRy2dOyJWR63oPVFhbfSc3hU1VkZzel/UWBdd6kLOXo2F0aUw5OzVWBmtHJt76wigHQvBmuhSE3JUaKyJdhwFNBZE27RrcqJorIguFSEnisai+HPXPu9jWXzuqgYfC+MLOok+VsWXjjMSlsRXdGp8LImvnfXvt45mNvWaHKE+VsW32ddkn/qVMOXx+LvJChN+qo7J2231hgR8nlR9WffKdvVJWs2Ph/pXpjhbv769NSdn+z8L1A6SVS9vOrE4iCUGxsrr12dNGLkCYebDw5TvAUGYZRNGrgaHqV5ogjALEGbZFyau30OBhAiwEunwLb8d6foKv/EVC5fv8YvFxo8DTO7CxN+rAWewWO5a7Omrd+AH3FxerWLh0MdVLNYphO+9QG4lyK3q8Y/Tp/TQWSnIUh9443yon3ObEBq0jnYmCwXJ68tAEASkQbuq1AYh1qBAiShXiQBfYgkgib4zQnMX1HgCaN9aekzP63919a/vKr767y6aWCCPrnY/3gKg5Wuw/JqEr10BckcdgCkhXPmvrz7BUAAzoQLmvCbgWkGcPu3KOBgerEH4btew/JgYdA9gwF3V3x0qYLGugq2cAvvhI6AJqlS4+uXkaepvhgFdsEzes8zKPzt+DgkIwH51FVYVIKy+bgS+IFeiP1dF+cUicFXA1VVacfrUKRAOHPk5x2rTMdWfGTQxwDboLEyypjloKN5Tj86xoMA2oF1yl26OpgL+wlVo1Y09AAXdXPWSWtY95dpTqi+ewcJBfXNXzqxTpTbBXIM6812FaiPYGqVGMmCgXXV6/GgdEAfjlLvmcOW226exvcWE0wh0p3TKBb13eYGPXGDZsp/2LsrT6mM/4A7noavDavf0UOQ74twiQLlLV9HCGO0DhQRVL50VUwaohTPVp+1ABsBB9HOwFOpVEOchCfSU/XraQFQE0A7SNUBAhIjmAeaudJVz9en8/gcaAQJkU7iy6WoCkEbtQq3eiYHOAz51+6/qA0U9DnxXaVfz03VOhHPFlUjw3qjxBENsUTOpN3ld/98na/3BY4foYOIoMWy9fXh7+xsDjQ4ShDoAAA=="; \ No newline at end of file diff --git a/classes/factory._internal_.Blob.html b/classes/factory._internal_.Blob.html new file mode 100644 index 0000000..fbf2066 --- /dev/null +++ b/classes/factory._internal_.Blob.html @@ -0,0 +1,33 @@ +
Creates a new Blob object containing a concatenation of the given sources.
{ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into +the 'Blob' and can therefore be safely modified after the 'Blob' is created.
+String sources are also copied into the Blob.
Optional options: BlobOptionsReadonly sizeThe total size of the Blob in bytes.
v15.7.0, v14.18.0
+Readonly typeThe content-type of the Blob.
v15.7.0, v14.18.0
+Returns a promise that fulfills with an ArrayBuffer containing a copy of
+the Blob data.
v15.7.0, v14.18.0
+Creates and returns a new Blob containing a subset of this Blob objects
+data. The original Blob is not altered.
Optional start: numberThe starting index.
+Optional end: numberThe ending index.
+Optional type: stringThe content-type for the new Blob
v15.7.0, v14.18.0
+Returns a new ReadableStream that allows the content of the Blob to be read.
v16.7.0
+Generated using TypeDoc
Instances of the readline.Interface class are constructed using thereadline.createInterface() method. Every instance is associated with a
+single input Readable stream and a single output Writable stream.
+The output stream is used to print prompts for user input that arrives on,
+and is read from, the input stream.
v0.1.104
+Protected constructorNOTE: According to the documentation:
+++Instances of the
+readline.Interfaceclass are constructed using the +readline.createInterface()method.
Optional output: WritableStreamOptional completer: Completer | AsyncCompleterOptional terminal: booleanNOTE: According to the documentation:
+++Instances of the
+readline.Interfaceclass are constructed using the +readline.createInterface()method.
Static Readonly errorThis symbol shall be used to install a listener for only monitoring 'error'
+events. Listeners installed using this symbol are called before the regular
+'error' listeners are called.
Installing a listener using this symbol does not change the behavior once an
+'error' event is emitted, therefore the process will still crash if no
+regular 'error' listener is installed.
Static Readonly captureStatic captureSets or gets the default captureRejection value for all emitters.
+Static defaultReadonly terminalReadonly lineThe current input data being processed by node.
+This can be used when collecting input from a TTY stream to retrieve the
+current value that has been processed thus far, prior to the line event
+being emitted. Once the line event has been emitted, this property will
+be an empty string.
Be aware that modifying the value during the instance runtime may have
+unintended consequences if rl.cursor is not also controlled.
If not using a TTY stream for input, use the 'line' event.
One possible use case would be as follows:
+const values = ['lorem ipsum', 'dolor sit amet'];
const rl = readline.createInterface(process.stdin);
const showResults = debounce(() => {
console.log(
'\n',
values.filter((val) => val.startsWith(rl.line)).join(' ')
);
}, 300);
process.stdin.on('keypress', (c, k) => {
showResults();
});
+
+v0.1.98
+Readonly cursorThe cursor position relative to rl.line.
This will track where the current cursor lands in the input string, when +reading input from a TTY stream. The position of cursor determines the +portion of the input string that will be modified as input is processed, +as well as the column where the terminal caret will be rendered.
+v0.1.98
+Optional [captureStatic onceCreates a Promise that is fulfilled when the EventEmitter emits the given
+event or that is rejected if the EventEmitter emits 'error' while waiting.
+The Promise will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error' event
+semantics and does not listen to the 'error' event.
const { once, EventEmitter } = require('events');
async function run() {
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.log('error happened', err);
}
}
run();
+
+The special handling of the 'error' event is only used when events.once()is used to wait for another event. If events.once() is used to wait for the
+'error' event itself, then it is treated as any other kind of event without
+special handling:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.log('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+An AbortSignal can be used to cancel waiting for the event:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+Optional options: StaticEventEmitterOptionsv11.13.0, v10.16.0
+Optional options: StaticEventEmitterOptionsStatic onconst { on, EventEmitter } = require('events');
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
+
+Returns an AsyncIterator that iterates eventName events. It will throw
+if the EventEmitter emits 'error'. It removes all listeners when
+exiting the loop. The value returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal can be used to cancel waiting on events:
const { on, EventEmitter } = require('events');
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+The name of the event being listened for
+Optional options: StaticEventEmitterOptionsthat iterates eventName events emitted by the emitter
v13.6.0, v12.16.0
+Static listenerA class method that returns the number of listeners for the given eventNameregistered on the given emitter.
const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+The emitter to query
+The event name
+v0.9.12
+Since v3.2.0 - Use listenerCount instead.
Static getReturns a copy of the array of listeners for the event named eventName.
For EventEmitters this behaves exactly the same as calling .listeners on
+the emitter.
For EventTargets this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
const { getEventListeners, EventEmitter } = require('events');
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
getEventListeners(ee, 'foo'); // [listener]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
getEventListeners(et, 'foo'); // [listener]
}
+
+v15.2.0, v14.17.0
+Static getReturns the currently set max amount of listeners.
+For EventEmitters this behaves exactly the same as calling .getMaxListeners on
+the emitter.
For EventTargets this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+v18.17.0
+Static setconst {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+Optional n: numberA non-negative number. The maximum number of listeners per EventTarget event.
Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]v15.4.0
+Static addExperimental Listens once to the abort event on the provided signal.
Listening to the abort event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignals in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+Disposable that removes the abort listener.
v18.18.0
+Removes the specified listener from the listener array for the event namedeventName.
const callback = (stream) => {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
+
+removeListener() will remove, at most, one instance of a listener from the
+listener array. If any single listener has been added multiple times to the
+listener array for the specified eventName, then removeListener() must be
+called multiple times to remove each instance.
Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that anyremoveListener() or removeAllListeners() calls after emitting and before the last listener finishes execution
+will not remove them fromemit() in progress. Subsequent events behave as expected.
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners() method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener() will remove the most
+recently added instance. In the example the once('ping')listener is removed:
const ee = new EventEmitter();
function pong() {
console.log('pong');
}
ee.on('ping', pong);
ee.once('ping', pong);
ee.removeListener('ping', pong);
ee.emit('ping');
ee.emit('ping');
+
+Returns a reference to the EventEmitter, so that calls can be chained.
Rest ...args: any[]v0.1.26
+Alias for emitter.removeListener().
Rest ...args: any[]v10.0.0
+Removes all listeners, or those of the specified eventName.
It is bad practice to remove listeners added elsewhere in the code,
+particularly when the EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter, so that calls can be chained.
Optional event: string | symbolv0.1.26
+By default EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter, so that calls can be chained.
v0.3.5
+Returns the current max listener value for the EventEmitter which is either
+set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.
v1.0.0
+Returns a copy of the array of listeners for the event named eventName.
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+
+v0.1.26
+Returns a copy of the array of listeners for the event named eventName,
+including any wrappers (such as those created by .once()).
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
// Returns a new Array with a function `onceWrapper` which has a property
// `listener` which contains the original listener bound above
const listeners = emitter.rawListeners('log');
const logFnWrapper = listeners[0];
// Logs "log once" to the console and does not unbind the `once` event
logFnWrapper.listener();
// Logs "log once" to the console and removes the listener
logFnWrapper();
emitter.on('log', () => console.log('log persistently'));
// Will return a new Array with a single function bound by `.on()` above
const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice
newListeners[0]();
emitter.emit('log');
+
+v9.4.0
+Returns the number of listeners listening to the event named eventName.
If listener is provided, it will return how many times the listener
+is found in the list of the listeners of the event.
The name of the event being listened for
+Optional listener: FunctionThe event handler function
+v3.2.0
+Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbols.
const EventEmitter = require('events');
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+v6.0.0
+The rl.prompt() method writes the readline.Interface instances configuredprompt to a new line in output in order to provide a user with a new
+location at which to provide input.
When called, rl.prompt() will resume the input stream if it has been
+paused.
If the readline.Interface was created with output set to null orundefined the prompt is not written.
Optional preserveCursor: booleanIf true, prevents the cursor placement from being reset to 0.
v0.1.98
+The rl.question() method displays the query by writing it to the output,
+waits for user input to be provided on input, then invokes the callbackfunction passing the provided input as the first argument.
When called, rl.question() will resume the input stream if it has been
+paused.
If the readline.Interface was created with output set to null orundefined the query is not written.
The callback function passed to rl.question() does not follow the typical
+pattern of accepting an Error object or null as the first argument.
+The callback is called with the provided answer as the only argument.
Example usage:
+rl.question('What is your favorite food? ', (answer) => {
console.log(`Oh, so your favorite food is ${answer}`);
});
+
+Using an AbortController to cancel a question.
const ac = new AbortController();
const signal = ac.signal;
rl.question('What is your favorite food? ', { signal }, (answer) => {
console.log(`Oh, so your favorite food is ${answer}`);
});
signal.addEventListener('abort', () => {
console.log('The food question timed out');
}, { once: true });
setTimeout(() => ac.abort(), 10000);
+
+If this method is invoked as it's util.promisify()ed version, it returns a
+Promise that fulfills with the answer. If the question is canceled using
+an AbortController it will reject with an AbortError.
const util = require('util');
const question = util.promisify(rl.question).bind(rl);
async function questionExample() {
try {
const answer = await question('What is you favorite food? ');
console.log(`Oh, so your favorite food is ${answer}`);
} catch (err) {
console.error('Question rejected', err);
}
}
questionExample();
+
+A statement or query to write to output, prepended to the prompt.
A callback function that is invoked with the user's input in response to the query.
v0.3.3
+The rl.close() method closes the readline.Interface instance and
+relinquishes control over the input and output streams. When called,
+the 'close' event will be emitted.
Calling rl.close() does not immediately stop other events (including 'line')
+from being emitted by the readline.Interface instance.
v0.1.98
+The rl.write() method will write either data or a key sequence identified
+by key to the output. The key argument is supported only if output is
+a TTY text terminal. See TTY keybindings for a list of key
+combinations.
If key is specified, data is ignored.
When called, rl.write() will resume the input stream if it has been
+paused.
If the readline.Interface was created with output set to null orundefined the data and key are not written.
rl.write('Delete this!');
// Simulate Ctrl+U to delete the line written previously
rl.write(null, { ctrl: true, name: 'u' });
+
+The rl.write() method will write the data to the readline Interface'sinputas if it were provided by the user.
v0.1.98
+events.EventEmitter
+Rest ...args: any[]Synchronously calls each of the listeners registered for the event namedeventName, in the order they were registered, passing the supplied arguments
+to each.
Returns true if the event had listeners, false otherwise.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
+
+Rest ...args: any[]v0.1.26
+Adds the listener function to the end of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple
+times.
server.on('connection', (stream) => {
console.log('someone connected!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. Theemitter.prependListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+The name of the event.
+The callback function
+Rest ...args: any[]v0.1.101
+Adds a one-timelistener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. Theemitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+The name of the event.
+The callback function
+Rest ...args: any[]v0.3.0
+Adds the listener function to the beginning of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple
+times.
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+Rest ...args: any[]v6.0.0
+Adds a one-timelistener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+Rest ...args: any[]v6.0.0
+Generated using TypeDoc
Node.js uses a KeyObject class to represent a symmetric or asymmetric key,
+and each kind of key exposes different functions. The createSecretKey, createPublicKey and createPrivateKey methods are used to create KeyObjectinstances. KeyObject
+objects are not to be created directly using the newkeyword.
Most applications should consider using the new KeyObject API instead of
+passing keys as strings or Buffers due to improved security features.
KeyObject instances can be passed to other threads via postMessage().
+The receiver obtains a cloned KeyObject, and the KeyObject does not need to
+be listed in the transferList argument.
v11.6.0
+Private constructorOptional asymmetricFor asymmetric keys, this property represents the type of the key. Supported key +types are:
+'rsa' (OID 1.2.840.113549.1.1.1)'rsa-pss' (OID 1.2.840.113549.1.1.10)'dsa' (OID 1.2.840.10040.4.1)'ec' (OID 1.2.840.10045.2.1)'x25519' (OID 1.3.101.110)'x448' (OID 1.3.101.111)'ed25519' (OID 1.3.101.112)'ed448' (OID 1.3.101.113)'dh' (OID 1.2.840.113549.1.3.1)This property is undefined for unrecognized KeyObject types and symmetric
+keys.
v11.6.0
+Optional asymmetricFor asymmetric keys, this property represents the size of the embedded key in
+bytes. This property is undefined for symmetric keys.
Optional asymmetricThis property exists only on asymmetric keys. Depending on the type of the key, +this object contains information about the key. None of the information obtained +through this property can be used to uniquely identify a key or to compromise +the security of the key.
+For RSA-PSS keys, if the key material contains a RSASSA-PSS-params sequence,
+the hashAlgorithm, mgf1HashAlgorithm, and saltLength properties will be
+set.
Other key details might be exposed via this API using additional attributes.
+v15.7.0
+Optional symmetricFor secret keys, this property represents the size of the key in bytes. This
+property is undefined for asymmetric keys.
v11.6.0
+Depending on the type of this KeyObject, this property is either'secret' for secret (symmetric) keys, 'public' for public (asymmetric) keys
+or 'private' for private (asymmetric) keys.
v11.6.0
+Static fromExample: Converting a CryptoKey instance to a KeyObject:
const { webcrypto, KeyObject } = await import('crypto');
const { subtle } = webcrypto;
const key = await subtle.generateKey({
name: 'HMAC',
hash: 'SHA-256',
length: 256
}, true, ['sign', 'verify']);
const keyObject = KeyObject.from(key);
console.log(keyObject.symmetricKeySize);
// Prints: 32 (symmetric key size in bytes)
+
+v15.0.0
+For symmetric keys, the following encoding options can be used:
+For public keys, the following encoding options can be used:
+For private keys, the following encoding options can be used:
+The result type depends on the selected encoding format, when PEM the +result is a string, when DER it will be a buffer containing the data +encoded as DER, when JWK it will be an object.
+When JWK encoding format was selected, all other encoding options are +ignored.
+PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of
+the cipher and format options. The PKCS#8 type can be used with anyformat to encrypt any key algorithm (RSA, EC, or DH) by specifying acipher. PKCS#1 and SEC1 can only be
+encrypted by specifying a cipherwhen the PEM format is used. For maximum compatibility, use PKCS#8 for
+encrypted private keys. Since PKCS#8 defines its own
+encryption mechanism, PEM-level encryption is not supported when encrypting
+a PKCS#8 key. See RFC 5208 for PKCS#8 encryption and RFC 1421 for
+PKCS#1 and SEC1 encryption.
v11.6.0
+Optional options: KeyExportOptions<"der">Optional options: JwkKeyExportOptionsReturns true or false depending on whether the keys have exactly the same type, value, and parameters.
+This method is not constant time.
v16.15.0
+Generated using TypeDoc
Instances of the worker.MessagePort class represent one end of an
+asynchronous, two-way communications channel. It can be used to transfer
+structured data, memory regions and other MessagePorts between different Worker s.
This implementation matches browser MessagePort s.
v10.5.0
+Optional options: EventEmitterOptionsStatic Readonly errorThis symbol shall be used to install a listener for only monitoring 'error'
+events. Listeners installed using this symbol are called before the regular
+'error' listeners are called.
Installing a listener using this symbol does not change the behavior once an
+'error' event is emitted, therefore the process will still crash if no
+regular 'error' listener is installed.
Static Readonly captureStatic captureSets or gets the default captureRejection value for all emitters.
+Static defaultOptional [captureStatic onceCreates a Promise that is fulfilled when the EventEmitter emits the given
+event or that is rejected if the EventEmitter emits 'error' while waiting.
+The Promise will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error' event
+semantics and does not listen to the 'error' event.
const { once, EventEmitter } = require('events');
async function run() {
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.log('error happened', err);
}
}
run();
+
+The special handling of the 'error' event is only used when events.once()is used to wait for another event. If events.once() is used to wait for the
+'error' event itself, then it is treated as any other kind of event without
+special handling:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.log('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+An AbortSignal can be used to cancel waiting for the event:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+Optional options: StaticEventEmitterOptionsv11.13.0, v10.16.0
+Optional options: StaticEventEmitterOptionsStatic onconst { on, EventEmitter } = require('events');
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
+
+Returns an AsyncIterator that iterates eventName events. It will throw
+if the EventEmitter emits 'error'. It removes all listeners when
+exiting the loop. The value returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal can be used to cancel waiting on events:
const { on, EventEmitter } = require('events');
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+The name of the event being listened for
+Optional options: StaticEventEmitterOptionsthat iterates eventName events emitted by the emitter
v13.6.0, v12.16.0
+Static listenerA class method that returns the number of listeners for the given eventNameregistered on the given emitter.
const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+The emitter to query
+The event name
+v0.9.12
+Since v3.2.0 - Use listenerCount instead.
Static getReturns a copy of the array of listeners for the event named eventName.
For EventEmitters this behaves exactly the same as calling .listeners on
+the emitter.
For EventTargets this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
const { getEventListeners, EventEmitter } = require('events');
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
getEventListeners(ee, 'foo'); // [listener]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
getEventListeners(et, 'foo'); // [listener]
}
+
+v15.2.0, v14.17.0
+Static getReturns the currently set max amount of listeners.
+For EventEmitters this behaves exactly the same as calling .getMaxListeners on
+the emitter.
For EventTargets this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+v18.17.0
+Static setconst {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+Optional n: numberA non-negative number. The maximum number of listeners per EventTarget event.
Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]v15.4.0
+Static addExperimental Listens once to the abort event on the provided signal.
Listening to the abort event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignals in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+Disposable that removes the abort listener.
v18.18.0
+Removes all listeners, or those of the specified eventName.
It is bad practice to remove listeners added elsewhere in the code,
+particularly when the EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter, so that calls can be chained.
Optional event: string | symbolv0.1.26
+By default EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter, so that calls can be chained.
v0.3.5
+Returns the current max listener value for the EventEmitter which is either
+set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.
v1.0.0
+Returns a copy of the array of listeners for the event named eventName.
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+
+v0.1.26
+Returns a copy of the array of listeners for the event named eventName,
+including any wrappers (such as those created by .once()).
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
// Returns a new Array with a function `onceWrapper` which has a property
// `listener` which contains the original listener bound above
const listeners = emitter.rawListeners('log');
const logFnWrapper = listeners[0];
// Logs "log once" to the console and does not unbind the `once` event
logFnWrapper.listener();
// Logs "log once" to the console and removes the listener
logFnWrapper();
emitter.on('log', () => console.log('log persistently'));
// Will return a new Array with a single function bound by `.on()` above
const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice
newListeners[0]();
emitter.emit('log');
+
+v9.4.0
+Returns the number of listeners listening to the event named eventName.
If listener is provided, it will return how many times the listener
+is found in the list of the listeners of the event.
The name of the event being listened for
+Optional listener: FunctionThe event handler function
+v3.2.0
+Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbols.
const EventEmitter = require('events');
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+v6.0.0
+Sends a JavaScript value to the receiving side of this channel.value is transferred in a way which is compatible with
+the HTML structured clone algorithm.
In particular, the significant differences to JSON are:
value may contain circular references.value may contain instances of builtin JS types such as RegExps,BigInts, Maps, Sets, etc.value may contain typed arrays, both using ArrayBuffers
+and SharedArrayBuffers.value may contain WebAssembly.Module instances.value may not contain native (C++-backed) objects other than:const { MessageChannel } = require('worker_threads');
const { port1, port2 } = new MessageChannel();
port1.on('message', (message) => console.log(message));
const circularData = {};
circularData.foo = circularData;
// Prints: { foo: [Circular] }
port2.postMessage(circularData);
+
+transferList may be a list of ArrayBuffer, MessagePort and FileHandle objects.
+After transferring, they are not usable on the sending side of the channel
+anymore (even if they are not contained in value). Unlike with child processes, transferring handles such as network sockets is currently
+not supported.
If value contains SharedArrayBuffer instances, those are accessible
+from either thread. They cannot be listed in transferList.
value may still contain ArrayBuffer instances that are not intransferList; in that case, the underlying memory is copied rather than moved.
const { MessageChannel } = require('worker_threads');
const { port1, port2 } = new MessageChannel();
port1.on('message', (message) => console.log(message));
const uint8Array = new Uint8Array([ 1, 2, 3, 4 ]);
// This posts a copy of `uint8Array`:
port2.postMessage(uint8Array);
// This does not copy data, but renders `uint8Array` unusable:
port2.postMessage(uint8Array, [ uint8Array.buffer ]);
// The memory for the `sharedUint8Array` is accessible from both the
// original and the copy received by `.on('message')`:
const sharedUint8Array = new Uint8Array(new SharedArrayBuffer(4));
port2.postMessage(sharedUint8Array);
// This transfers a freshly created message port to the receiver.
// This can be used, for example, to create communication channels between
// multiple `Worker` threads that are children of the same parent thread.
const otherChannel = new MessageChannel();
port2.postMessage({ port: otherChannel.port1 }, [ otherChannel.port1 ]);
+
+The message object is cloned immediately, and can be modified after +posting without having side effects.
+For more information on the serialization and deserialization mechanisms
+behind this API, see the serialization API of the v8 module.
Optional transferList: readonly TransferListItem[]v10.5.0
+Opposite of unref(). Calling ref() on a previously unref()ed port does not let the program exit if it's the only active handle left (the default
+behavior). If the port is ref()ed, calling ref() again has no effect.
If listeners are attached or removed using .on('message'), the port
+is ref()ed and unref()ed automatically depending on whether
+listeners for the event exist.
v10.5.0
+Calling unref() on a port allows the thread to exit if this is the only
+active handle in the event system. If the port is already unref()ed callingunref() again has no effect.
If listeners are attached or removed using .on('message'), the port isref()ed and unref()ed automatically depending on whether
+listeners for the event exist.
v10.5.0
+Starts receiving messages on this MessagePort. When using this port
+as an event emitter, this is called automatically once 'message'listeners are attached.
This method exists for parity with the Web MessagePort API. In Node.js,
+it is only useful for ignoring messages when no event listener is present.
+Node.js also diverges in its handling of .onmessage. Setting it
+automatically calls .start(), but unsetting it lets messages queue up
+until a new handler is set or the port is discarded.
v10.5.0
+Alias for emitter.on(eventName, listener).
v0.1.26
+Rest ...args: any[]Synchronously calls each of the listeners registered for the event namedeventName, in the order they were registered, passing the supplied arguments
+to each.
Returns true if the event had listeners, false otherwise.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
+
+v0.1.26
+Rest ...args: any[]Adds the listener function to the end of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple
+times.
server.on('connection', (stream) => {
console.log('someone connected!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. Theemitter.prependListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+The name of the event.
+The callback function
+v0.1.101
+Rest ...args: any[]Adds a one-timelistener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. Theemitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+The name of the event.
+The callback function
+v0.3.0
+Rest ...args: any[]Adds the listener function to the beginning of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple
+times.
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+v6.0.0
+Rest ...args: any[]Adds a one-timelistener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+v6.0.0
+Rest ...args: any[]Removes the specified listener from the listener array for the event namedeventName.
const callback = (stream) => {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
+
+removeListener() will remove, at most, one instance of a listener from the
+listener array. If any single listener has been added multiple times to the
+listener array for the specified eventName, then removeListener() must be
+called multiple times to remove each instance.
Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that anyremoveListener() or removeAllListeners() calls after emitting and before the last listener finishes execution
+will not remove them fromemit() in progress. Subsequent events behave as expected.
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners() method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener() will remove the most
+recently added instance. In the example the once('ping')listener is removed:
const ee = new EventEmitter();
function pong() {
console.log('pong');
}
ee.on('ping', pong);
ee.once('ping', pong);
ee.removeListener('ping', pong);
ee.emit('ping');
ee.emit('ping');
+
+Returns a reference to the EventEmitter, so that calls can be chained.
v0.1.26
+Rest ...args: any[]Alias for emitter.removeListener().
v10.0.0
+Rest ...args: any[]Generated using TypeDoc
Instances of fs.ReadStream are created and returned using the createReadStream function.
v0.1.93
+Optional opts: ReadableOptionsStatic Readonly errorThis symbol shall be used to install a listener for only monitoring 'error'
+events. Listeners installed using this symbol are called before the regular
+'error' listeners are called.
Installing a listener using this symbol does not change the behavior once an
+'error' event is emitted, therefore the process will still crash if no
+regular 'error' listener is installed.
Static Readonly captureStatic captureSets or gets the default captureRejection value for all emitters.
+Static defaultThe number of bytes that have been read so far.
+v6.4.0
+The path to the file the stream is reading from as specified in the first
+argument to fs.createReadStream(). If path is passed as a string, thenreadStream.path will be a string. If path is passed as a Buffer, thenreadStream.path will be a
+Buffer. If fd is specified, thenreadStream.path will be undefined.
v0.1.93
+This property is true if the underlying file has not been opened yet,
+i.e. before the 'ready' event is emitted.
v11.2.0, v10.16.0
+Readonly Experimental readableReturns whether the stream was destroyed or errored before emitting 'end'.
v16.8.0
+Is true if it is safe to call readable.read(), which means
+the stream has not been destroyed or emitted 'error' or 'end'.
v11.4.0
+Readonly Experimental readableReturns whether 'data' has been emitted.
v16.7.0, v14.18.0
+Readonly readableGetter for the property encoding of a given Readable stream. The encodingproperty can be set using the readable.setEncoding() method.
v12.7.0
+Readonly readableBecomes true when 'end' event is emitted.
v12.9.0
+Readonly readableThis property reflects the current state of a Readable stream as described
+in the Three states section.
v9.4.0
+Readonly readableReturns the value of highWaterMark passed when creating this Readable.
v9.3.0
+Readonly readableThis property contains the number of bytes (or objects) in the queue
+ready to be read. The value provides introspection data regarding
+the status of the highWaterMark.
v9.4.0
+Readonly readableGetter for the property objectMode of a given Readable stream.
v12.3.0
+Is true after readable.destroy() has been called.
v8.0.0
+Readonly closedIs true after 'close' has been emitted.
+v18.0.0
+Readonly erroredReturns error if the stream has been destroyed with an error.
+v18.0.0
+Optional [captureStatic onceCreates a Promise that is fulfilled when the EventEmitter emits the given
+event or that is rejected if the EventEmitter emits 'error' while waiting.
+The Promise will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error' event
+semantics and does not listen to the 'error' event.
const { once, EventEmitter } = require('events');
async function run() {
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.log('error happened', err);
}
}
run();
+
+The special handling of the 'error' event is only used when events.once()is used to wait for another event. If events.once() is used to wait for the
+'error' event itself, then it is treated as any other kind of event without
+special handling:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.log('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+An AbortSignal can be used to cancel waiting for the event:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+Optional options: StaticEventEmitterOptionsv11.13.0, v10.16.0
+Optional options: StaticEventEmitterOptionsStatic onconst { on, EventEmitter } = require('events');
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
+
+Returns an AsyncIterator that iterates eventName events. It will throw
+if the EventEmitter emits 'error'. It removes all listeners when
+exiting the loop. The value returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal can be used to cancel waiting on events:
const { on, EventEmitter } = require('events');
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+The name of the event being listened for
+Optional options: StaticEventEmitterOptionsthat iterates eventName events emitted by the emitter
v13.6.0, v12.16.0
+Static listenerA class method that returns the number of listeners for the given eventNameregistered on the given emitter.
const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+The emitter to query
+The event name
+v0.9.12
+Since v3.2.0 - Use listenerCount instead.
Static getReturns a copy of the array of listeners for the event named eventName.
For EventEmitters this behaves exactly the same as calling .listeners on
+the emitter.
For EventTargets this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
const { getEventListeners, EventEmitter } = require('events');
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
getEventListeners(ee, 'foo'); // [listener]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
getEventListeners(et, 'foo'); // [listener]
}
+
+v15.2.0, v14.17.0
+Static getReturns the currently set max amount of listeners.
+For EventEmitters this behaves exactly the same as calling .getMaxListeners on
+the emitter.
For EventTargets this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+v18.17.0
+Static setconst {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+Optional n: numberA non-negative number. The maximum number of listeners per EventTarget event.
Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]v15.4.0
+Static addExperimental Listens once to the abort event on the provided signal.
Listening to the abort event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignals in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+Disposable that removes the abort listener.
v18.18.0
+Alias for emitter.removeListener().
Rest ...args: any[]v10.0.0
+Removes all listeners, or those of the specified eventName.
It is bad practice to remove listeners added elsewhere in the code,
+particularly when the EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter, so that calls can be chained.
Optional event: string | symbolv0.1.26
+By default EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter, so that calls can be chained.
v0.3.5
+Returns the current max listener value for the EventEmitter which is either
+set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.
v1.0.0
+Returns a copy of the array of listeners for the event named eventName.
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+
+v0.1.26
+Returns a copy of the array of listeners for the event named eventName,
+including any wrappers (such as those created by .once()).
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
// Returns a new Array with a function `onceWrapper` which has a property
// `listener` which contains the original listener bound above
const listeners = emitter.rawListeners('log');
const logFnWrapper = listeners[0];
// Logs "log once" to the console and does not unbind the `once` event
logFnWrapper.listener();
// Logs "log once" to the console and removes the listener
logFnWrapper();
emitter.on('log', () => console.log('log persistently'));
// Will return a new Array with a single function bound by `.on()` above
const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice
newListeners[0]();
emitter.emit('log');
+
+v9.4.0
+Returns the number of listeners listening to the event named eventName.
If listener is provided, it will return how many times the listener
+is found in the list of the listeners of the event.
The name of the event being listened for
+Optional listener: FunctionThe event handler function
+v3.2.0
+Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbols.
const EventEmitter = require('events');
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+v6.0.0
+Optional callback: ((err?) => void)Optional err: ErrnoExceptionevents.EventEmitter
+Rest ...args: any[]Adds the listener function to the end of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple
+times.
server.on('connection', (stream) => {
console.log('someone connected!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. Theemitter.prependListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+The name of the event.
+The callback function
+v0.1.101
+Rest ...args: any[]Adds a one-timelistener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. Theemitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+The name of the event.
+The callback function
+v0.3.0
+Rest ...args: any[]Adds the listener function to the beginning of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple
+times.
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+v6.0.0
+Rest ...args: any[]Adds a one-timelistener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+v6.0.0
+Rest ...args: any[]Optional options: { Optional end?: booleanOptional options: { Static fromA utility method for creating Readable Streams out of iterators.
+Optional options: ReadableOptionsStatic fromExperimental A utility method for creating a Readable from a web ReadableStream.
Optional options: Pick<ReadableOptions, "encoding" | "highWaterMark" | "objectMode" | "signal">v17.0.0
+Static isReturns whether the stream has been read from or cancelled.
+v16.8.0
+Static toExperimental A utility method for creating a web ReadableStream from a Readable.
v17.0.0
+Optional _constructThe readable.read() method reads data out of the internal buffer and
+returns it. If no data is available to be read, null is returned. By default,
+the data is returned as a Buffer object unless an encoding has been
+specified using the readable.setEncoding() method or the stream is operating
+in object mode.
The optional size argument specifies a specific number of bytes to read. Ifsize bytes are not available to be read, null will be returned _unless_the stream has ended, in which
+case all of the data remaining in the internal
+buffer will be returned.
If the size argument is not specified, all of the data contained in the
+internal buffer will be returned.
The size argument must be less than or equal to 1 GiB.
The readable.read() method should only be called on Readable streams
+operating in paused mode. In flowing mode, readable.read() is called
+automatically until the internal buffer is fully drained.
const readable = getReadableStreamSomehow();
// 'readable' may be triggered multiple times as data is buffered in
readable.on('readable', () => {
let chunk;
console.log('Stream is readable (new data received in buffer)');
// Use a loop to make sure we read all currently available data
while (null !== (chunk = readable.read())) {
console.log(`Read ${chunk.length} bytes of data...`);
}
});
// 'end' will be triggered once when there is no more data available
readable.on('end', () => {
console.log('Reached end of stream.');
});
+
+Each call to readable.read() returns a chunk of data, or null. The chunks
+are not concatenated. A while loop is necessary to consume all data
+currently in the buffer. When reading a large file .read() may return null,
+having consumed all buffered content so far, but there is still more data to
+come not yet buffered. In this case a new 'readable' event will be emitted
+when there is more data in the buffer. Finally the 'end' event will be
+emitted when there is no more data to come.
Therefore to read a file's whole contents from a readable, it is necessary
+to collect chunks across multiple 'readable' events:
const chunks = [];
readable.on('readable', () => {
let chunk;
while (null !== (chunk = readable.read())) {
chunks.push(chunk);
}
});
readable.on('end', () => {
const content = chunks.join('');
});
+
+A Readable stream in object mode will always return a single item from
+a call to readable.read(size), regardless of the value of thesize argument.
If the readable.read() method returns a chunk of data, a 'data' event will
+also be emitted.
Calling read after the 'end' event has
+been emitted will return null. No runtime error will be raised.
Optional size: numberOptional argument to specify how much data to read.
+v0.9.4
+The readable.setEncoding() method sets the character encoding for
+data read from the Readable stream.
By default, no encoding is assigned and stream data will be returned asBuffer objects. Setting an encoding causes the stream data
+to be returned as strings of the specified encoding rather than as Bufferobjects. For instance, calling readable.setEncoding('utf8') will cause the
+output data to be interpreted as UTF-8 data, and passed as strings. Callingreadable.setEncoding('hex') will cause the data to be encoded in hexadecimal
+string format.
The Readable stream will properly handle multi-byte characters delivered
+through the stream that would otherwise become improperly decoded if simply
+pulled from the stream as Buffer objects.
const readable = getReadableStreamSomehow();
readable.setEncoding('utf8');
readable.on('data', (chunk) => {
assert.equal(typeof chunk, 'string');
console.log('Got %d characters of string data:', chunk.length);
});
+
+The encoding to use.
+v0.9.4
+The readable.pause() method will cause a stream in flowing mode to stop
+emitting 'data' events, switching out of flowing mode. Any data that
+becomes available will remain in the internal buffer.
const readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
readable.pause();
console.log('There will be no additional data for 1 second.');
setTimeout(() => {
console.log('Now data will start flowing again.');
readable.resume();
}, 1000);
});
+
+The readable.pause() method has no effect if there is a 'readable'event listener.
v0.9.4
+The readable.resume() method causes an explicitly paused Readable stream to
+resume emitting 'data' events, switching the stream into flowing mode.
The readable.resume() method can be used to fully consume the data from a
+stream without actually processing any of that data:
getReadableStreamSomehow()
.resume()
.on('end', () => {
console.log('Reached the end, but did not read anything.');
});
+
+The readable.resume() method has no effect if there is a 'readable'event listener.
v0.9.4
+The readable.isPaused() method returns the current operating state of theReadable. This is used primarily by the mechanism that underlies thereadable.pipe() method. In most
+typical cases, there will be no reason to
+use this method directly.
const readable = new stream.Readable();
readable.isPaused(); // === false
readable.pause();
readable.isPaused(); // === true
readable.resume();
readable.isPaused(); // === false
+
+v0.11.14
+The readable.unpipe() method detaches a Writable stream previously attached
+using the pipe method.
If the destination is not specified, then all pipes are detached.
If the destination is specified, but no pipe is set up for it, then
+the method does nothing.
const fs = require('fs');
const readable = getReadableStreamSomehow();
const writable = fs.createWriteStream('file.txt');
// All the data from readable goes into 'file.txt',
// but only for the first second.
readable.pipe(writable);
setTimeout(() => {
console.log('Stop writing to file.txt.');
readable.unpipe(writable);
console.log('Manually close the file stream.');
writable.end();
}, 1000);
+
+Optional destination: WritableStreamOptional specific stream to unpipe
+v0.9.4
+Passing chunk as null signals the end of the stream (EOF) and behaves the
+same as readable.push(null), after which no more data can be written. The EOF
+signal is put at the end of the buffer and any buffered data will still be
+flushed.
The readable.unshift() method pushes a chunk of data back into the internal
+buffer. This is useful in certain situations where a stream is being consumed by
+code that needs to "un-consume" some amount of data that it has optimistically
+pulled out of the source, so that the data can be passed on to some other party.
The stream.unshift(chunk) method cannot be called after the 'end' event
+has been emitted or a runtime error will be thrown.
Developers using stream.unshift() often should consider switching to
+use of a Transform stream instead. See the API for stream implementers section for more information.
// Pull off a header delimited by \n\n.
// Use unshift() if we get too much.
// Call the callback with (error, header, stream).
const { StringDecoder } = require('string_decoder');
function parseHeader(stream, callback) {
stream.on('error', callback);
stream.on('readable', onReadable);
const decoder = new StringDecoder('utf8');
let header = '';
function onReadable() {
let chunk;
while (null !== (chunk = stream.read())) {
const str = decoder.write(chunk);
if (str.includes('\n\n')) {
// Found the header boundary.
const split = str.split(/\n\n/);
header += split.shift();
const remaining = split.join('\n\n');
const buf = Buffer.from(remaining, 'utf8');
stream.removeListener('error', callback);
// Remove the 'readable' listener before unshifting.
stream.removeListener('readable', onReadable);
if (buf.length)
stream.unshift(buf);
// Now the body of the message can be read from the stream.
callback(null, header, stream);
return;
}
// Still reading the header.
header += str;
}
}
}
+
+Unlike push, stream.unshift(chunk) will not
+end the reading process by resetting the internal reading state of the stream.
+This can cause unexpected results if readable.unshift() is called during a
+read (i.e. from within a _read implementation on a
+custom stream). Following the call to readable.unshift() with an immediate push will reset the reading state appropriately,
+however it is best to simply avoid calling readable.unshift() while in the
+process of performing a read.
Chunk of data to unshift onto the read queue. For streams not operating in object mode, chunk must be a string, Buffer, Uint8Array or null. For object mode
+streams, chunk may be any JavaScript value.
Optional encoding: BufferEncodingEncoding of string chunks. Must be a valid Buffer encoding, such as 'utf8' or 'ascii'.
v0.9.11
+Prior to Node.js 0.10, streams did not implement the entire stream module API
+as it is currently defined. (See Compatibility for more information.)
When using an older Node.js library that emits 'data' events and has a pause method that is advisory only, thereadable.wrap() method can be used to create a Readable
+stream that uses
+the old stream as its data source.
It will rarely be necessary to use readable.wrap() but the method has been
+provided as a convenience for interacting with older Node.js applications and
+libraries.
const { OldReader } = require('./old-api-module.js');
const { Readable } = require('stream');
const oreader = new OldReader();
const myReader = new Readable().wrap(oreader);
myReader.on('readable', () => {
myReader.read(); // etc.
});
+
+An "old style" readable stream
+v0.9.4
+Optional encoding: BufferEncodingThe iterator created by this method gives users the option to cancel the destruction
+of the stream if the for await...of loop is exited by return, break, or throw,
+or if the iterator should destroy the stream if the stream emitted an error during iteration.
Optional options: { Optional destroyWhen set to false, calling return on the async iterator,
+or exiting a for await...of iteration using a break, return, or throw will not destroy the stream.
+Default: true.
v16.3.0
+This method allows mapping over the stream. The fn function will be called for every chunk in the stream.
+If the fn function returns a promise - that promise will be awaited before being passed to the result stream.
a function to map over every chunk in the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa stream mapped with the function fn.
+v17.4.0, v16.14.0
+This method allows filtering the stream. For each chunk in the stream the fn function will be called
+and if it returns a truthy value, the chunk will be passed to the result stream.
+If the fn function returns a promise - that promise will be awaited.
a function to filter chunks from the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa stream filtered with the predicate fn.
+v17.4.0, v16.14.0
+This method allows iterating a stream. For each chunk in the stream the fn function will be called.
+If the fn function returns a promise - that promise will be awaited.
This method is different from for await...of loops in that it can optionally process chunks concurrently.
+In addition, a forEach iteration can only be stopped by having passed a signal option
+and aborting the related AbortController while for await...of can be stopped with break or return.
+In either case the stream will be destroyed.
This method is different from listening to the 'data' event in that it uses the readable event
+in the underlying machinary and can limit the number of concurrent fn calls.
a function to call on each chunk of the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa promise for when the stream has finished.
+v17.5.0
+This method allows easily obtaining the contents of a stream.
+As this method reads the entire stream into memory, it negates the benefits of streams. It's intended +for interoperability and convenience, not as the primary way to consume streams.
+Optional options: Pick<ArrayOptions, "signal">a promise containing an array with the contents of the stream.
+v17.5.0
+This method is similar to Array.prototype.some and calls fn on each chunk in the stream
+until the awaited return value is true (or any truthy value). Once an fn call on a chunk
+awaited return value is truthy, the stream is destroyed and the promise is fulfilled with true.
+If none of the fn calls on the chunks return a truthy value, the promise is fulfilled with false.
a function to call on each chunk of the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa promise evaluating to true if fn returned a truthy value for at least one of the chunks.
v17.5.0
+This method is similar to Array.prototype.find and calls fn on each chunk in the stream
+to find a chunk with a truthy value for fn. Once an fn call's awaited return value is truthy,
+the stream is destroyed and the promise is fulfilled with value for which fn returned a truthy value.
+If all of the fn calls on the chunks return a falsy value, the promise is fulfilled with undefined.
a function to call on each chunk of the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa promise evaluating to the first chunk for which fn evaluated with a truthy value,
+or undefined if no element was found.
v17.5.0
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsThis method is similar to Array.prototype.every and calls fn on each chunk in the stream
+to check if all awaited return values are truthy value for fn. Once an fn call on a chunk
+awaited return value is falsy, the stream is destroyed and the promise is fulfilled with false.
+If all of the fn calls on the chunks return a truthy value, the promise is fulfilled with true.
a function to call on each chunk of the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa promise evaluating to true if fn returned a truthy value for every one of the chunks.
v17.5.0
+This method returns a new stream by applying the given callback to each chunk of the stream +and then flattening the result.
+It is possible to return a stream or another iterable or async iterable from fn and the result streams +will be merged (flattened) into the returned stream.
+a function to map over every chunk in the stream. May be async. May be a stream or generator.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa stream flat-mapped with the function fn.
+v17.5.0
+This method returns a new stream with the first limit chunks dropped from the start.
+the number of chunks to drop from the readable.
+Optional options: Pick<ArrayOptions, "signal">a stream with limit chunks dropped from the start.
+v17.5.0
+This method returns a new stream with the first limit chunks.
+the number of chunks to take from the readable.
+Optional options: Pick<ArrayOptions, "signal">a stream with limit chunks taken.
+v17.5.0
+This method returns a new stream with chunks of the underlying stream paired with a counter
+in the form [index, chunk]. The first index value is 0 and it increases by 1 for each chunk produced.
Optional options: Pick<ArrayOptions, "signal">a stream of indexed pairs.
+v17.5.0
+This method calls fn on each chunk of the stream in order, passing it the result from the calculation +on the previous element. It returns a promise for the final value of the reduction.
+If no initial value is supplied the first chunk of the stream is used as the initial value.
+If the stream is empty, the promise is rejected with a TypeError with the ERR_INVALID_ARGS code property.
The reducer function iterates the stream element-by-element which means that there is no concurrency parameter
+or parallelism. To perform a reduce concurrently, you can extract the async function to readable.map method.
a reducer function to call over every chunk in the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional initial: undefinedthe initial value to use in the reduction.
+Optional options: Pick<ArrayOptions, "signal">a promise for the final value of the reduction.
+v17.5.0
+Optional options: Pick<ArrayOptions, "signal">Optional options: Pick<ArrayOptions, "signal">Destroy the stream. Optionally emit an 'error' event, and emit a 'close'event (unless emitClose is set to false). After this call, the readable
+stream will release any internal resources and subsequent calls to push()will be ignored.
Once destroy() has been called any further calls will be a no-op and no
+further errors except from _destroy() may be emitted as 'error'.
Implementors should not override this method, but instead implement readable._destroy().
Optional error: ErrorError which will be passed as payload in 'error' event
v8.0.0
+Synchronously calls each of the listeners registered for the event namedeventName, in the order they were registered, passing the supplied arguments
+to each.
Returns true if the event had listeners, false otherwise.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
+
+v0.1.26
+Rest ...args: any[]Removes the specified listener from the listener array for the event namedeventName.
const callback = (stream) => {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
+
+removeListener() will remove, at most, one instance of a listener from the
+listener array. If any single listener has been added multiple times to the
+listener array for the specified eventName, then removeListener() must be
+called multiple times to remove each instance.
Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that anyremoveListener() or removeAllListeners() calls after emitting and before the last listener finishes execution
+will not remove them fromemit() in progress. Subsequent events behave as expected.
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners() method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener() will remove the most
+recently added instance. In the example the once('ping')listener is removed:
const ee = new EventEmitter();
function pong() {
console.log('pong');
}
ee.on('ping', pong);
ee.once('ping', pong);
ee.removeListener('ping', pong);
ee.emit('ping');
ee.emit('ping');
+
+Returns a reference to the EventEmitter, so that calls can be chained.
v0.1.26
+Rest ...args: any[]Generated using TypeDoc
v0.9.4
+Optional opts: ReadableOptionsStatic Readonly errorThis symbol shall be used to install a listener for only monitoring 'error'
+events. Listeners installed using this symbol are called before the regular
+'error' listeners are called.
Installing a listener using this symbol does not change the behavior once an
+'error' event is emitted, therefore the process will still crash if no
+regular 'error' listener is installed.
Static Readonly captureStatic captureSets or gets the default captureRejection value for all emitters.
+Static defaultReadonly Experimental readableReturns whether the stream was destroyed or errored before emitting 'end'.
v16.8.0
+Is true if it is safe to call readable.read(), which means
+the stream has not been destroyed or emitted 'error' or 'end'.
v11.4.0
+Readonly Experimental readableReturns whether 'data' has been emitted.
v16.7.0, v14.18.0
+Readonly readableGetter for the property encoding of a given Readable stream. The encodingproperty can be set using the readable.setEncoding() method.
v12.7.0
+Readonly readableBecomes true when 'end' event is emitted.
v12.9.0
+Readonly readableThis property reflects the current state of a Readable stream as described
+in the Three states section.
v9.4.0
+Readonly readableReturns the value of highWaterMark passed when creating this Readable.
v9.3.0
+Readonly readableThis property contains the number of bytes (or objects) in the queue
+ready to be read. The value provides introspection data regarding
+the status of the highWaterMark.
v9.4.0
+Readonly readableGetter for the property objectMode of a given Readable stream.
v12.3.0
+Is true after readable.destroy() has been called.
v8.0.0
+Readonly closedIs true after 'close' has been emitted.
+v18.0.0
+Readonly erroredReturns error if the stream has been destroyed with an error.
+v18.0.0
+Optional [captureStatic onceCreates a Promise that is fulfilled when the EventEmitter emits the given
+event or that is rejected if the EventEmitter emits 'error' while waiting.
+The Promise will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error' event
+semantics and does not listen to the 'error' event.
const { once, EventEmitter } = require('events');
async function run() {
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.log('error happened', err);
}
}
run();
+
+The special handling of the 'error' event is only used when events.once()is used to wait for another event. If events.once() is used to wait for the
+'error' event itself, then it is treated as any other kind of event without
+special handling:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.log('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+An AbortSignal can be used to cancel waiting for the event:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+Optional options: StaticEventEmitterOptionsv11.13.0, v10.16.0
+Optional options: StaticEventEmitterOptionsStatic onconst { on, EventEmitter } = require('events');
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
+
+Returns an AsyncIterator that iterates eventName events. It will throw
+if the EventEmitter emits 'error'. It removes all listeners when
+exiting the loop. The value returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal can be used to cancel waiting on events:
const { on, EventEmitter } = require('events');
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+The name of the event being listened for
+Optional options: StaticEventEmitterOptionsthat iterates eventName events emitted by the emitter
v13.6.0, v12.16.0
+Static listenerA class method that returns the number of listeners for the given eventNameregistered on the given emitter.
const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+The emitter to query
+The event name
+v0.9.12
+Since v3.2.0 - Use listenerCount instead.
Static getReturns a copy of the array of listeners for the event named eventName.
For EventEmitters this behaves exactly the same as calling .listeners on
+the emitter.
For EventTargets this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
const { getEventListeners, EventEmitter } = require('events');
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
getEventListeners(ee, 'foo'); // [listener]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
getEventListeners(et, 'foo'); // [listener]
}
+
+v15.2.0, v14.17.0
+Static getReturns the currently set max amount of listeners.
+For EventEmitters this behaves exactly the same as calling .getMaxListeners on
+the emitter.
For EventTargets this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+v18.17.0
+Static setconst {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+Optional n: numberA non-negative number. The maximum number of listeners per EventTarget event.
Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]v15.4.0
+Static addExperimental Listens once to the abort event on the provided signal.
Listening to the abort event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignals in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+Disposable that removes the abort listener.
v18.18.0
+Alias for emitter.removeListener().
Rest ...args: any[]v10.0.0
+Removes all listeners, or those of the specified eventName.
It is bad practice to remove listeners added elsewhere in the code,
+particularly when the EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter, so that calls can be chained.
Optional event: string | symbolv0.1.26
+By default EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter, so that calls can be chained.
v0.3.5
+Returns the current max listener value for the EventEmitter which is either
+set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.
v1.0.0
+Returns a copy of the array of listeners for the event named eventName.
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+
+v0.1.26
+Returns a copy of the array of listeners for the event named eventName,
+including any wrappers (such as those created by .once()).
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
// Returns a new Array with a function `onceWrapper` which has a property
// `listener` which contains the original listener bound above
const listeners = emitter.rawListeners('log');
const logFnWrapper = listeners[0];
// Logs "log once" to the console and does not unbind the `once` event
logFnWrapper.listener();
// Logs "log once" to the console and removes the listener
logFnWrapper();
emitter.on('log', () => console.log('log persistently'));
// Will return a new Array with a single function bound by `.on()` above
const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice
newListeners[0]();
emitter.emit('log');
+
+v9.4.0
+Returns the number of listeners listening to the event named eventName.
If listener is provided, it will return how many times the listener
+is found in the list of the listeners of the event.
The name of the event being listened for
+Optional listener: FunctionThe event handler function
+v3.2.0
+Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbols.
const EventEmitter = require('events');
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+v6.0.0
+Optional options: { Optional end?: booleanOptional options: { Static fromA utility method for creating Readable Streams out of iterators.
+Optional options: ReadableOptionsStatic fromExperimental A utility method for creating a Readable from a web ReadableStream.
Optional options: Pick<ReadableOptions, "encoding" | "highWaterMark" | "objectMode" | "signal">v17.0.0
+Static isReturns whether the stream has been read from or cancelled.
+v16.8.0
+Static toExperimental A utility method for creating a web ReadableStream from a Readable.
v17.0.0
+Optional _constructThe readable.read() method reads data out of the internal buffer and
+returns it. If no data is available to be read, null is returned. By default,
+the data is returned as a Buffer object unless an encoding has been
+specified using the readable.setEncoding() method or the stream is operating
+in object mode.
The optional size argument specifies a specific number of bytes to read. Ifsize bytes are not available to be read, null will be returned _unless_the stream has ended, in which
+case all of the data remaining in the internal
+buffer will be returned.
If the size argument is not specified, all of the data contained in the
+internal buffer will be returned.
The size argument must be less than or equal to 1 GiB.
The readable.read() method should only be called on Readable streams
+operating in paused mode. In flowing mode, readable.read() is called
+automatically until the internal buffer is fully drained.
const readable = getReadableStreamSomehow();
// 'readable' may be triggered multiple times as data is buffered in
readable.on('readable', () => {
let chunk;
console.log('Stream is readable (new data received in buffer)');
// Use a loop to make sure we read all currently available data
while (null !== (chunk = readable.read())) {
console.log(`Read ${chunk.length} bytes of data...`);
}
});
// 'end' will be triggered once when there is no more data available
readable.on('end', () => {
console.log('Reached end of stream.');
});
+
+Each call to readable.read() returns a chunk of data, or null. The chunks
+are not concatenated. A while loop is necessary to consume all data
+currently in the buffer. When reading a large file .read() may return null,
+having consumed all buffered content so far, but there is still more data to
+come not yet buffered. In this case a new 'readable' event will be emitted
+when there is more data in the buffer. Finally the 'end' event will be
+emitted when there is no more data to come.
Therefore to read a file's whole contents from a readable, it is necessary
+to collect chunks across multiple 'readable' events:
const chunks = [];
readable.on('readable', () => {
let chunk;
while (null !== (chunk = readable.read())) {
chunks.push(chunk);
}
});
readable.on('end', () => {
const content = chunks.join('');
});
+
+A Readable stream in object mode will always return a single item from
+a call to readable.read(size), regardless of the value of thesize argument.
If the readable.read() method returns a chunk of data, a 'data' event will
+also be emitted.
Calling read after the 'end' event has
+been emitted will return null. No runtime error will be raised.
Optional size: numberOptional argument to specify how much data to read.
+v0.9.4
+The readable.setEncoding() method sets the character encoding for
+data read from the Readable stream.
By default, no encoding is assigned and stream data will be returned asBuffer objects. Setting an encoding causes the stream data
+to be returned as strings of the specified encoding rather than as Bufferobjects. For instance, calling readable.setEncoding('utf8') will cause the
+output data to be interpreted as UTF-8 data, and passed as strings. Callingreadable.setEncoding('hex') will cause the data to be encoded in hexadecimal
+string format.
The Readable stream will properly handle multi-byte characters delivered
+through the stream that would otherwise become improperly decoded if simply
+pulled from the stream as Buffer objects.
const readable = getReadableStreamSomehow();
readable.setEncoding('utf8');
readable.on('data', (chunk) => {
assert.equal(typeof chunk, 'string');
console.log('Got %d characters of string data:', chunk.length);
});
+
+The encoding to use.
+v0.9.4
+The readable.pause() method will cause a stream in flowing mode to stop
+emitting 'data' events, switching out of flowing mode. Any data that
+becomes available will remain in the internal buffer.
const readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
readable.pause();
console.log('There will be no additional data for 1 second.');
setTimeout(() => {
console.log('Now data will start flowing again.');
readable.resume();
}, 1000);
});
+
+The readable.pause() method has no effect if there is a 'readable'event listener.
v0.9.4
+The readable.resume() method causes an explicitly paused Readable stream to
+resume emitting 'data' events, switching the stream into flowing mode.
The readable.resume() method can be used to fully consume the data from a
+stream without actually processing any of that data:
getReadableStreamSomehow()
.resume()
.on('end', () => {
console.log('Reached the end, but did not read anything.');
});
+
+The readable.resume() method has no effect if there is a 'readable'event listener.
v0.9.4
+The readable.isPaused() method returns the current operating state of theReadable. This is used primarily by the mechanism that underlies thereadable.pipe() method. In most
+typical cases, there will be no reason to
+use this method directly.
const readable = new stream.Readable();
readable.isPaused(); // === false
readable.pause();
readable.isPaused(); // === true
readable.resume();
readable.isPaused(); // === false
+
+v0.11.14
+The readable.unpipe() method detaches a Writable stream previously attached
+using the pipe method.
If the destination is not specified, then all pipes are detached.
If the destination is specified, but no pipe is set up for it, then
+the method does nothing.
const fs = require('fs');
const readable = getReadableStreamSomehow();
const writable = fs.createWriteStream('file.txt');
// All the data from readable goes into 'file.txt',
// but only for the first second.
readable.pipe(writable);
setTimeout(() => {
console.log('Stop writing to file.txt.');
readable.unpipe(writable);
console.log('Manually close the file stream.');
writable.end();
}, 1000);
+
+Optional destination: WritableStreamOptional specific stream to unpipe
+v0.9.4
+Passing chunk as null signals the end of the stream (EOF) and behaves the
+same as readable.push(null), after which no more data can be written. The EOF
+signal is put at the end of the buffer and any buffered data will still be
+flushed.
The readable.unshift() method pushes a chunk of data back into the internal
+buffer. This is useful in certain situations where a stream is being consumed by
+code that needs to "un-consume" some amount of data that it has optimistically
+pulled out of the source, so that the data can be passed on to some other party.
The stream.unshift(chunk) method cannot be called after the 'end' event
+has been emitted or a runtime error will be thrown.
Developers using stream.unshift() often should consider switching to
+use of a Transform stream instead. See the API for stream implementers section for more information.
// Pull off a header delimited by \n\n.
// Use unshift() if we get too much.
// Call the callback with (error, header, stream).
const { StringDecoder } = require('string_decoder');
function parseHeader(stream, callback) {
stream.on('error', callback);
stream.on('readable', onReadable);
const decoder = new StringDecoder('utf8');
let header = '';
function onReadable() {
let chunk;
while (null !== (chunk = stream.read())) {
const str = decoder.write(chunk);
if (str.includes('\n\n')) {
// Found the header boundary.
const split = str.split(/\n\n/);
header += split.shift();
const remaining = split.join('\n\n');
const buf = Buffer.from(remaining, 'utf8');
stream.removeListener('error', callback);
// Remove the 'readable' listener before unshifting.
stream.removeListener('readable', onReadable);
if (buf.length)
stream.unshift(buf);
// Now the body of the message can be read from the stream.
callback(null, header, stream);
return;
}
// Still reading the header.
header += str;
}
}
}
+
+Unlike push, stream.unshift(chunk) will not
+end the reading process by resetting the internal reading state of the stream.
+This can cause unexpected results if readable.unshift() is called during a
+read (i.e. from within a _read implementation on a
+custom stream). Following the call to readable.unshift() with an immediate push will reset the reading state appropriately,
+however it is best to simply avoid calling readable.unshift() while in the
+process of performing a read.
Chunk of data to unshift onto the read queue. For streams not operating in object mode, chunk must be a string, Buffer, Uint8Array or null. For object mode
+streams, chunk may be any JavaScript value.
Optional encoding: BufferEncodingEncoding of string chunks. Must be a valid Buffer encoding, such as 'utf8' or 'ascii'.
v0.9.11
+Prior to Node.js 0.10, streams did not implement the entire stream module API
+as it is currently defined. (See Compatibility for more information.)
When using an older Node.js library that emits 'data' events and has a pause method that is advisory only, thereadable.wrap() method can be used to create a Readable
+stream that uses
+the old stream as its data source.
It will rarely be necessary to use readable.wrap() but the method has been
+provided as a convenience for interacting with older Node.js applications and
+libraries.
const { OldReader } = require('./old-api-module.js');
const { Readable } = require('stream');
const oreader = new OldReader();
const myReader = new Readable().wrap(oreader);
myReader.on('readable', () => {
myReader.read(); // etc.
});
+
+An "old style" readable stream
+v0.9.4
+Optional encoding: BufferEncodingThe iterator created by this method gives users the option to cancel the destruction
+of the stream if the for await...of loop is exited by return, break, or throw,
+or if the iterator should destroy the stream if the stream emitted an error during iteration.
Optional options: { Optional destroyWhen set to false, calling return on the async iterator,
+or exiting a for await...of iteration using a break, return, or throw will not destroy the stream.
+Default: true.
v16.3.0
+This method allows mapping over the stream. The fn function will be called for every chunk in the stream.
+If the fn function returns a promise - that promise will be awaited before being passed to the result stream.
a function to map over every chunk in the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa stream mapped with the function fn.
+v17.4.0, v16.14.0
+This method allows filtering the stream. For each chunk in the stream the fn function will be called
+and if it returns a truthy value, the chunk will be passed to the result stream.
+If the fn function returns a promise - that promise will be awaited.
a function to filter chunks from the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa stream filtered with the predicate fn.
+v17.4.0, v16.14.0
+This method allows iterating a stream. For each chunk in the stream the fn function will be called.
+If the fn function returns a promise - that promise will be awaited.
This method is different from for await...of loops in that it can optionally process chunks concurrently.
+In addition, a forEach iteration can only be stopped by having passed a signal option
+and aborting the related AbortController while for await...of can be stopped with break or return.
+In either case the stream will be destroyed.
This method is different from listening to the 'data' event in that it uses the readable event
+in the underlying machinary and can limit the number of concurrent fn calls.
a function to call on each chunk of the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa promise for when the stream has finished.
+v17.5.0
+This method allows easily obtaining the contents of a stream.
+As this method reads the entire stream into memory, it negates the benefits of streams. It's intended +for interoperability and convenience, not as the primary way to consume streams.
+Optional options: Pick<ArrayOptions, "signal">a promise containing an array with the contents of the stream.
+v17.5.0
+This method is similar to Array.prototype.some and calls fn on each chunk in the stream
+until the awaited return value is true (or any truthy value). Once an fn call on a chunk
+awaited return value is truthy, the stream is destroyed and the promise is fulfilled with true.
+If none of the fn calls on the chunks return a truthy value, the promise is fulfilled with false.
a function to call on each chunk of the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa promise evaluating to true if fn returned a truthy value for at least one of the chunks.
v17.5.0
+This method is similar to Array.prototype.find and calls fn on each chunk in the stream
+to find a chunk with a truthy value for fn. Once an fn call's awaited return value is truthy,
+the stream is destroyed and the promise is fulfilled with value for which fn returned a truthy value.
+If all of the fn calls on the chunks return a falsy value, the promise is fulfilled with undefined.
a function to call on each chunk of the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa promise evaluating to the first chunk for which fn evaluated with a truthy value,
+or undefined if no element was found.
v17.5.0
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsThis method is similar to Array.prototype.every and calls fn on each chunk in the stream
+to check if all awaited return values are truthy value for fn. Once an fn call on a chunk
+awaited return value is falsy, the stream is destroyed and the promise is fulfilled with false.
+If all of the fn calls on the chunks return a truthy value, the promise is fulfilled with true.
a function to call on each chunk of the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa promise evaluating to true if fn returned a truthy value for every one of the chunks.
v17.5.0
+This method returns a new stream by applying the given callback to each chunk of the stream +and then flattening the result.
+It is possible to return a stream or another iterable or async iterable from fn and the result streams +will be merged (flattened) into the returned stream.
+a function to map over every chunk in the stream. May be async. May be a stream or generator.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa stream flat-mapped with the function fn.
+v17.5.0
+This method returns a new stream with the first limit chunks dropped from the start.
+the number of chunks to drop from the readable.
+Optional options: Pick<ArrayOptions, "signal">a stream with limit chunks dropped from the start.
+v17.5.0
+This method returns a new stream with the first limit chunks.
+the number of chunks to take from the readable.
+Optional options: Pick<ArrayOptions, "signal">a stream with limit chunks taken.
+v17.5.0
+This method returns a new stream with chunks of the underlying stream paired with a counter
+in the form [index, chunk]. The first index value is 0 and it increases by 1 for each chunk produced.
Optional options: Pick<ArrayOptions, "signal">a stream of indexed pairs.
+v17.5.0
+This method calls fn on each chunk of the stream in order, passing it the result from the calculation +on the previous element. It returns a promise for the final value of the reduction.
+If no initial value is supplied the first chunk of the stream is used as the initial value.
+If the stream is empty, the promise is rejected with a TypeError with the ERR_INVALID_ARGS code property.
The reducer function iterates the stream element-by-element which means that there is no concurrency parameter
+or parallelism. To perform a reduce concurrently, you can extract the async function to readable.map method.
a reducer function to call over every chunk in the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional initial: undefinedthe initial value to use in the reduction.
+Optional options: Pick<ArrayOptions, "signal">a promise for the final value of the reduction.
+v17.5.0
+Optional options: Pick<ArrayOptions, "signal">Optional options: Pick<ArrayOptions, "signal">Destroy the stream. Optionally emit an 'error' event, and emit a 'close'event (unless emitClose is set to false). After this call, the readable
+stream will release any internal resources and subsequent calls to push()will be ignored.
Once destroy() has been called any further calls will be a no-op and no
+further errors except from _destroy() may be emitted as 'error'.
Implementors should not override this method, but instead implement readable._destroy().
Optional error: ErrorError which will be passed as payload in 'error' event
v8.0.0
+Event emitter +The defined events on documents including:
+Rest ...args: any[]Synchronously calls each of the listeners registered for the event namedeventName, in the order they were registered, passing the supplied arguments
+to each.
Returns true if the event had listeners, false otherwise.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
+
+v0.1.26
+Rest ...args: any[]Adds the listener function to the end of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple
+times.
server.on('connection', (stream) => {
console.log('someone connected!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. Theemitter.prependListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+The name of the event.
+The callback function
+v0.1.101
+Rest ...args: any[]Adds a one-timelistener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. Theemitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+The name of the event.
+The callback function
+v0.3.0
+Rest ...args: any[]Adds the listener function to the beginning of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple
+times.
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+v6.0.0
+Rest ...args: any[]Adds a one-timelistener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+v6.0.0
+Rest ...args: any[]Removes the specified listener from the listener array for the event namedeventName.
const callback = (stream) => {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
+
+removeListener() will remove, at most, one instance of a listener from the
+listener array. If any single listener has been added multiple times to the
+listener array for the specified eventName, then removeListener() must be
+called multiple times to remove each instance.
Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that anyremoveListener() or removeAllListeners() calls after emitting and before the last listener finishes execution
+will not remove them fromemit() in progress. Subsequent events behave as expected.
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners() method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener() will remove the most
+recently added instance. In the example the once('ping')listener is removed:
const ee = new EventEmitter();
function pong() {
console.log('pong');
}
ee.on('ping', pong);
ee.once('ping', pong);
ee.removeListener('ping', pong);
ee.emit('ping');
ee.emit('ping');
+
+Returns a reference to the EventEmitter, so that calls can be chained.
v0.1.26
+Rest ...args: any[]Generated using TypeDoc
A fs.Stats object provides information about a file.
Objects returned from stat, lstat and fstat and
+their synchronous counterparts are of this type.
+If bigint in the options passed to those methods is true, the numeric values
+will be bigint instead of number, and the object will contain additional
+nanosecond-precision properties suffixed with Ns.
Stats {
dev: 2114,
ino: 48064969,
mode: 33188,
nlink: 1,
uid: 85,
gid: 100,
rdev: 0,
size: 527,
blksize: 4096,
blocks: 8,
atimeMs: 1318289051000.1,
mtimeMs: 1318289051000.1,
ctimeMs: 1318289051000.1,
birthtimeMs: 1318289051000.1,
atime: Mon, 10 Oct 2011 23:24:11 GMT,
mtime: Mon, 10 Oct 2011 23:24:11 GMT,
ctime: Mon, 10 Oct 2011 23:24:11 GMT,
birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
+
+bigint version:
BigIntStats {
dev: 2114n,
ino: 48064969n,
mode: 33188n,
nlink: 1n,
uid: 85n,
gid: 100n,
rdev: 0n,
size: 527n,
blksize: 4096n,
blocks: 8n,
atimeMs: 1318289051000n,
mtimeMs: 1318289051000n,
ctimeMs: 1318289051000n,
birthtimeMs: 1318289051000n,
atimeNs: 1318289051000000000n,
mtimeNs: 1318289051000000000n,
ctimeNs: 1318289051000000000n,
birthtimeNs: 1318289051000000000n,
atime: Mon, 10 Oct 2011 23:24:11 GMT,
mtime: Mon, 10 Oct 2011 23:24:11 GMT,
ctime: Mon, 10 Oct 2011 23:24:11 GMT,
birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
+
+v0.1.21
+Generated using TypeDoc
The EventEmitter class is defined and exposed by the events module:
const EventEmitter = require('events');
+
+All EventEmitters emit the event 'newListener' when new listeners are
+added and 'removeListener' when existing listeners are removed.
It supports the following option:
+v0.1.26
+Optional opts: ReadableOptionsStatic Readonly errorThis symbol shall be used to install a listener for only monitoring 'error'
+events. Listeners installed using this symbol are called before the regular
+'error' listeners are called.
Installing a listener using this symbol does not change the behavior once an
+'error' event is emitted, therefore the process will still crash if no
+regular 'error' listener is installed.
Static Readonly captureStatic captureSets or gets the default captureRejection value for all emitters.
+Static defaultOptional [captureStatic onceCreates a Promise that is fulfilled when the EventEmitter emits the given
+event or that is rejected if the EventEmitter emits 'error' while waiting.
+The Promise will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error' event
+semantics and does not listen to the 'error' event.
const { once, EventEmitter } = require('events');
async function run() {
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.log('error happened', err);
}
}
run();
+
+The special handling of the 'error' event is only used when events.once()is used to wait for another event. If events.once() is used to wait for the
+'error' event itself, then it is treated as any other kind of event without
+special handling:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.log('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+An AbortSignal can be used to cancel waiting for the event:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+Optional options: StaticEventEmitterOptionsv11.13.0, v10.16.0
+Optional options: StaticEventEmitterOptionsStatic onconst { on, EventEmitter } = require('events');
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
+
+Returns an AsyncIterator that iterates eventName events. It will throw
+if the EventEmitter emits 'error'. It removes all listeners when
+exiting the loop. The value returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal can be used to cancel waiting on events:
const { on, EventEmitter } = require('events');
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+The name of the event being listened for
+Optional options: StaticEventEmitterOptionsthat iterates eventName events emitted by the emitter
v13.6.0, v12.16.0
+Static listenerA class method that returns the number of listeners for the given eventNameregistered on the given emitter.
const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+The emitter to query
+The event name
+v0.9.12
+Since v3.2.0 - Use listenerCount instead.
Static getReturns a copy of the array of listeners for the event named eventName.
For EventEmitters this behaves exactly the same as calling .listeners on
+the emitter.
For EventTargets this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
const { getEventListeners, EventEmitter } = require('events');
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
getEventListeners(ee, 'foo'); // [listener]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
getEventListeners(et, 'foo'); // [listener]
}
+
+v15.2.0, v14.17.0
+Static getReturns the currently set max amount of listeners.
+For EventEmitters this behaves exactly the same as calling .getMaxListeners on
+the emitter.
For EventTargets this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+v18.17.0
+Static setconst {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+Optional n: numberA non-negative number. The maximum number of listeners per EventTarget event.
Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]v15.4.0
+Static addExperimental Listens once to the abort event on the provided signal.
Listening to the abort event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignals in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+Disposable that removes the abort listener.
v18.18.0
+Alias for emitter.on(eventName, listener).
Rest ...args: any[]v0.1.26
+Adds the listener function to the end of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple
+times.
server.on('connection', (stream) => {
console.log('someone connected!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. Theemitter.prependListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+The name of the event.
+The callback function
+Rest ...args: any[]v0.1.101
+Adds a one-timelistener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. Theemitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+The name of the event.
+The callback function
+Rest ...args: any[]v0.3.0
+Removes the specified listener from the listener array for the event namedeventName.
const callback = (stream) => {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
+
+removeListener() will remove, at most, one instance of a listener from the
+listener array. If any single listener has been added multiple times to the
+listener array for the specified eventName, then removeListener() must be
+called multiple times to remove each instance.
Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that anyremoveListener() or removeAllListeners() calls after emitting and before the last listener finishes execution
+will not remove them fromemit() in progress. Subsequent events behave as expected.
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners() method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener() will remove the most
+recently added instance. In the example the once('ping')listener is removed:
const ee = new EventEmitter();
function pong() {
console.log('pong');
}
ee.on('ping', pong);
ee.once('ping', pong);
ee.removeListener('ping', pong);
ee.emit('ping');
ee.emit('ping');
+
+Returns a reference to the EventEmitter, so that calls can be chained.
Rest ...args: any[]v0.1.26
+Alias for emitter.removeListener().
Rest ...args: any[]v10.0.0
+Removes all listeners, or those of the specified eventName.
It is bad practice to remove listeners added elsewhere in the code,
+particularly when the EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter, so that calls can be chained.
Optional event: string | symbolv0.1.26
+By default EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter, so that calls can be chained.
v0.3.5
+Returns the current max listener value for the EventEmitter which is either
+set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.
v1.0.0
+Returns a copy of the array of listeners for the event named eventName.
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+
+v0.1.26
+Returns a copy of the array of listeners for the event named eventName,
+including any wrappers (such as those created by .once()).
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
// Returns a new Array with a function `onceWrapper` which has a property
// `listener` which contains the original listener bound above
const listeners = emitter.rawListeners('log');
const logFnWrapper = listeners[0];
// Logs "log once" to the console and does not unbind the `once` event
logFnWrapper.listener();
// Logs "log once" to the console and removes the listener
logFnWrapper();
emitter.on('log', () => console.log('log persistently'));
// Will return a new Array with a single function bound by `.on()` above
const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice
newListeners[0]();
emitter.emit('log');
+
+v9.4.0
+Synchronously calls each of the listeners registered for the event namedeventName, in the order they were registered, passing the supplied arguments
+to each.
Returns true if the event had listeners, false otherwise.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
+
+Rest ...args: AnyRestv0.1.26
+Returns the number of listeners listening to the event named eventName.
If listener is provided, it will return how many times the listener
+is found in the list of the listeners of the event.
The name of the event being listened for
+Optional listener: FunctionThe event handler function
+v3.2.0
+Adds the listener function to the beginning of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple
+times.
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+Rest ...args: any[]v6.0.0
+Adds a one-timelistener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+Rest ...args: any[]v6.0.0
+Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbols.
const EventEmitter = require('events');
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+v6.0.0
+Optional options: { Optional end?: booleanOptional options: { Generated using TypeDoc
v0.9.4
+Optional opts: WritableOptionsStatic Readonly errorThis symbol shall be used to install a listener for only monitoring 'error'
+events. Listeners installed using this symbol are called before the regular
+'error' listeners are called.
Installing a listener using this symbol does not change the behavior once an
+'error' event is emitted, therefore the process will still crash if no
+regular 'error' listener is installed.
Static Readonly captureStatic captureSets or gets the default captureRejection value for all emitters.
+Static defaultReadonly writableIs true if it is safe to call writable.write(), which means
+the stream has not been destroyed, errored or ended.
v11.4.0
+Readonly writableIs true after writable.end() has been called. This property
+does not indicate whether the data has been flushed, for this use writable.writableFinished instead.
v12.9.0
+Readonly writableIs set to true immediately before the 'finish' event is emitted.
v12.6.0
+Readonly writableReturn the value of highWaterMark passed when creating this Writable.
v9.3.0
+Readonly writableThis property contains the number of bytes (or objects) in the queue
+ready to be written. The value provides introspection data regarding
+the status of the highWaterMark.
v9.4.0
+Readonly writableGetter for the property objectMode of a given Writable stream.
v12.3.0
+Readonly writableNumber of times writable.uncork() needs to be
+called in order to fully uncork the stream.
v13.2.0, v12.16.0
+Is true after writable.destroy() has been called.
v8.0.0
+Readonly closedIs true after 'close' has been emitted.
+v18.0.0
+Readonly erroredReturns error if the stream has been destroyed with an error.
+v18.0.0
+Readonly writableIs true if the stream's buffer has been full and stream will emit 'drain'.
v15.2.0, v14.17.0
+Optional [captureStatic onceCreates a Promise that is fulfilled when the EventEmitter emits the given
+event or that is rejected if the EventEmitter emits 'error' while waiting.
+The Promise will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error' event
+semantics and does not listen to the 'error' event.
const { once, EventEmitter } = require('events');
async function run() {
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.log('error happened', err);
}
}
run();
+
+The special handling of the 'error' event is only used when events.once()is used to wait for another event. If events.once() is used to wait for the
+'error' event itself, then it is treated as any other kind of event without
+special handling:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.log('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+An AbortSignal can be used to cancel waiting for the event:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+Optional options: StaticEventEmitterOptionsv11.13.0, v10.16.0
+Optional options: StaticEventEmitterOptionsStatic onconst { on, EventEmitter } = require('events');
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
+
+Returns an AsyncIterator that iterates eventName events. It will throw
+if the EventEmitter emits 'error'. It removes all listeners when
+exiting the loop. The value returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal can be used to cancel waiting on events:
const { on, EventEmitter } = require('events');
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+The name of the event being listened for
+Optional options: StaticEventEmitterOptionsthat iterates eventName events emitted by the emitter
v13.6.0, v12.16.0
+Static listenerA class method that returns the number of listeners for the given eventNameregistered on the given emitter.
const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+The emitter to query
+The event name
+v0.9.12
+Since v3.2.0 - Use listenerCount instead.
Static getReturns a copy of the array of listeners for the event named eventName.
For EventEmitters this behaves exactly the same as calling .listeners on
+the emitter.
For EventTargets this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
const { getEventListeners, EventEmitter } = require('events');
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
getEventListeners(ee, 'foo'); // [listener]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
getEventListeners(et, 'foo'); // [listener]
}
+
+v15.2.0, v14.17.0
+Static getReturns the currently set max amount of listeners.
+For EventEmitters this behaves exactly the same as calling .getMaxListeners on
+the emitter.
For EventTargets this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+v18.17.0
+Static setconst {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+Optional n: numberA non-negative number. The maximum number of listeners per EventTarget event.
Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]v15.4.0
+Static addExperimental Listens once to the abort event on the provided signal.
Listening to the abort event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignals in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+Disposable that removes the abort listener.
v18.18.0
+Alias for emitter.removeListener().
Rest ...args: any[]v10.0.0
+Removes all listeners, or those of the specified eventName.
It is bad practice to remove listeners added elsewhere in the code,
+particularly when the EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter, so that calls can be chained.
Optional event: string | symbolv0.1.26
+By default EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter, so that calls can be chained.
v0.3.5
+Returns the current max listener value for the EventEmitter which is either
+set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.
v1.0.0
+Returns a copy of the array of listeners for the event named eventName.
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+
+v0.1.26
+Returns a copy of the array of listeners for the event named eventName,
+including any wrappers (such as those created by .once()).
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
// Returns a new Array with a function `onceWrapper` which has a property
// `listener` which contains the original listener bound above
const listeners = emitter.rawListeners('log');
const logFnWrapper = listeners[0];
// Logs "log once" to the console and does not unbind the `once` event
logFnWrapper.listener();
// Logs "log once" to the console and removes the listener
logFnWrapper();
emitter.on('log', () => console.log('log persistently'));
// Will return a new Array with a single function bound by `.on()` above
const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice
newListeners[0]();
emitter.emit('log');
+
+v9.4.0
+Returns the number of listeners listening to the event named eventName.
If listener is provided, it will return how many times the listener
+is found in the list of the listeners of the event.
The name of the event being listened for
+Optional listener: FunctionThe event handler function
+v3.2.0
+Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbols.
const EventEmitter = require('events');
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+v6.0.0
+Optional options: { Optional end?: booleanOptional options: { Static fromExperimental A utility method for creating a Writable from a web WritableStream.
Optional options: Pick<WritableOptions, "highWaterMark" | "objectMode" | "signal" | "decodeStrings">v17.0.0
+Static toExperimental A utility method for creating a web WritableStream from a Writable.
v17.0.0
+Optional error: ErrorOptional _writevOptional error: ErrorOptional _constructThe writable.write() method writes some data to the stream, and calls the
+supplied callback once the data has been fully handled. If an error
+occurs, the callback will be called with the error as its
+first argument. The callback is called asynchronously and before 'error' is
+emitted.
The return value is true if the internal buffer is less than thehighWaterMark configured when the stream was created after admitting chunk.
+If false is returned, further attempts to write data to the stream should
+stop until the 'drain' event is emitted.
While a stream is not draining, calls to write() will buffer chunk, and
+return false. Once all currently buffered chunks are drained (accepted for
+delivery by the operating system), the 'drain' event will be emitted.
+Once write() returns false, do not write more chunks
+until the 'drain' event is emitted. While calling write() on a stream that
+is not draining is allowed, Node.js will buffer all written chunks until
+maximum memory usage occurs, at which point it will abort unconditionally.
+Even before it aborts, high memory usage will cause poor garbage collector
+performance and high RSS (which is not typically released back to the system,
+even after the memory is no longer required). Since TCP sockets may never
+drain if the remote peer does not read the data, writing a socket that is
+not draining may lead to a remotely exploitable vulnerability.
Writing data while the stream is not draining is particularly
+problematic for a Transform, because the Transform streams are paused
+by default until they are piped or a 'data' or 'readable' event handler
+is added.
If the data to be written can be generated or fetched on demand, it is
+recommended to encapsulate the logic into a Readable and use pipe. However, if calling write() is preferred, it is
+possible to respect backpressure and avoid memory issues using the 'drain' event:
function write(data, cb) {
if (!stream.write(data)) {
stream.once('drain', cb);
} else {
process.nextTick(cb);
}
}
// Wait for cb to be called before doing any other write.
write('hello', () => {
console.log('Write completed, do more writes now.');
});
+
+A Writable stream in object mode will always ignore the encoding argument.
Optional data to write. For streams not operating in object mode, chunk must be a string, Buffer or Uint8Array. For object mode streams, chunk may be any
+JavaScript value other than null.
Optional callback: ((error) => void)Callback for when this chunk of data is flushed.
+false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.
v0.9.4
+Optional callback: ((error) => void)The writable.setDefaultEncoding() method sets the default encoding for a Writable stream.
The new default encoding
+v0.11.15
+Calling the writable.end() method signals that no more data will be written
+to the Writable. The optional chunk and encoding arguments allow one
+final additional chunk of data to be written immediately before closing the
+stream.
Calling the write method after calling end will raise an error.
+// Write 'hello, ' and then end with 'world!'.
const fs = require('fs');
const file = fs.createWriteStream('example.txt');
file.write('hello, ');
file.end('world!');
// Writing more now is not allowed!
+
+Optional cb: (() => void)v0.9.4
+Optional cb: (() => void)Optional cb: (() => void)The writable.cork() method forces all written data to be buffered in memory.
+The buffered data will be flushed when either the uncork or end methods are called.
The primary intent of writable.cork() is to accommodate a situation in which
+several small chunks are written to the stream in rapid succession. Instead of
+immediately forwarding them to the underlying destination, writable.cork()buffers all the chunks until writable.uncork() is called, which will pass them
+all to writable._writev(), if present. This prevents a head-of-line blocking
+situation where data is being buffered while waiting for the first small chunk
+to be processed. However, use of writable.cork() without implementingwritable._writev() may have an adverse effect on throughput.
See also: writable.uncork(), writable._writev().
v0.11.2
+The writable.uncork() method flushes all data buffered since cork was called.
When using writable.cork() and writable.uncork() to manage the buffering
+of writes to a stream, defer calls to writable.uncork() usingprocess.nextTick(). Doing so allows batching of allwritable.write() calls that occur within a given Node.js event
+loop phase.
stream.cork();
stream.write('some ');
stream.write('data ');
process.nextTick(() => stream.uncork());
+
+If the writable.cork() method is called multiple times on a stream, the
+same number of calls to writable.uncork() must be called to flush the buffered
+data.
stream.cork();
stream.write('some ');
stream.cork();
stream.write('data ');
process.nextTick(() => {
stream.uncork();
// The data will not be flushed until uncork() is called a second time.
stream.uncork();
});
+
+See also: writable.cork().
v0.11.2
+Destroy the stream. Optionally emit an 'error' event, and emit a 'close'event (unless emitClose is set to false). After this call, the writable
+stream has ended and subsequent calls to write() or end() will result in
+an ERR_STREAM_DESTROYED error.
+This is a destructive and immediate way to destroy a stream. Previous calls towrite() may not have drained, and may trigger an ERR_STREAM_DESTROYED error.
+Use end() instead of destroy if data should flush before close, or wait for
+the 'drain' event before destroying the stream.
Once destroy() has been called any further calls will be a no-op and no
+further errors except from _destroy() may be emitted as 'error'.
Implementors should not override this method,
+but instead implement writable._destroy().
Optional error: ErrorOptional, an error to emit with 'error' event.
v8.0.0
+Event emitter +The defined events on documents including:
+Rest ...args: any[]Synchronously calls each of the listeners registered for the event namedeventName, in the order they were registered, passing the supplied arguments
+to each.
Returns true if the event had listeners, false otherwise.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
+
+v0.1.26
+Rest ...args: any[]Adds the listener function to the end of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple
+times.
server.on('connection', (stream) => {
console.log('someone connected!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. Theemitter.prependListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+The name of the event.
+The callback function
+v0.1.101
+Rest ...args: any[]Adds a one-timelistener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. Theemitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+The name of the event.
+The callback function
+v0.3.0
+Rest ...args: any[]Adds the listener function to the beginning of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple
+times.
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+v6.0.0
+Rest ...args: any[]Adds a one-timelistener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+v6.0.0
+Rest ...args: any[]Removes the specified listener from the listener array for the event namedeventName.
const callback = (stream) => {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
+
+removeListener() will remove, at most, one instance of a listener from the
+listener array. If any single listener has been added multiple times to the
+listener array for the specified eventName, then removeListener() must be
+called multiple times to remove each instance.
Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that anyremoveListener() or removeAllListeners() calls after emitting and before the last listener finishes execution
+will not remove them fromemit() in progress. Subsequent events behave as expected.
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners() method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener() will remove the most
+recently added instance. In the example the once('ping')listener is removed:
const ee = new EventEmitter();
function pong() {
console.log('pong');
}
ee.on('ping', pong);
ee.once('ping', pong);
ee.removeListener('ping', pong);
ee.emit('ping');
ee.emit('ping');
+
+Returns a reference to the EventEmitter, so that calls can be chained.
v0.1.26
+Rest ...args: any[]Generated using TypeDoc
stream.WritableInstances of fs.WriteStream are created and returned using the createWriteStream function.
v0.1.93
+Optional opts: WritableOptionsStatic Readonly errorThis symbol shall be used to install a listener for only monitoring 'error'
+events. Listeners installed using this symbol are called before the regular
+'error' listeners are called.
Installing a listener using this symbol does not change the behavior once an
+'error' event is emitted, therefore the process will still crash if no
+regular 'error' listener is installed.
Static Readonly captureStatic captureSets or gets the default captureRejection value for all emitters.
+Static defaultThe number of bytes written so far. Does not include data that is still queued +for writing.
+v0.4.7
+The path to the file the stream is writing to as specified in the first
+argument to createWriteStream. If path is passed as a string, thenwriteStream.path will be a string. If path is passed as a Buffer, thenwriteStream.path will be a
+Buffer.
v0.1.93
+This property is true if the underlying file has not been opened yet,
+i.e. before the 'ready' event is emitted.
v11.2.0
+Readonly writableIs true if it is safe to call writable.write(), which means
+the stream has not been destroyed, errored or ended.
v11.4.0
+Readonly writableIs true after writable.end() has been called. This property
+does not indicate whether the data has been flushed, for this use writable.writableFinished instead.
v12.9.0
+Readonly writableIs set to true immediately before the 'finish' event is emitted.
v12.6.0
+Readonly writableReturn the value of highWaterMark passed when creating this Writable.
v9.3.0
+Readonly writableThis property contains the number of bytes (or objects) in the queue
+ready to be written. The value provides introspection data regarding
+the status of the highWaterMark.
v9.4.0
+Readonly writableGetter for the property objectMode of a given Writable stream.
v12.3.0
+Readonly writableNumber of times writable.uncork() needs to be
+called in order to fully uncork the stream.
v13.2.0, v12.16.0
+Is true after writable.destroy() has been called.
v8.0.0
+Readonly closedIs true after 'close' has been emitted.
+v18.0.0
+Readonly erroredReturns error if the stream has been destroyed with an error.
+v18.0.0
+Readonly writableIs true if the stream's buffer has been full and stream will emit 'drain'.
v15.2.0, v14.17.0
+Optional [captureStatic onceCreates a Promise that is fulfilled when the EventEmitter emits the given
+event or that is rejected if the EventEmitter emits 'error' while waiting.
+The Promise will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error' event
+semantics and does not listen to the 'error' event.
const { once, EventEmitter } = require('events');
async function run() {
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.log('error happened', err);
}
}
run();
+
+The special handling of the 'error' event is only used when events.once()is used to wait for another event. If events.once() is used to wait for the
+'error' event itself, then it is treated as any other kind of event without
+special handling:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.log('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+An AbortSignal can be used to cancel waiting for the event:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+Optional options: StaticEventEmitterOptionsv11.13.0, v10.16.0
+Optional options: StaticEventEmitterOptionsStatic onconst { on, EventEmitter } = require('events');
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
+
+Returns an AsyncIterator that iterates eventName events. It will throw
+if the EventEmitter emits 'error'. It removes all listeners when
+exiting the loop. The value returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal can be used to cancel waiting on events:
const { on, EventEmitter } = require('events');
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+The name of the event being listened for
+Optional options: StaticEventEmitterOptionsthat iterates eventName events emitted by the emitter
v13.6.0, v12.16.0
+Static listenerA class method that returns the number of listeners for the given eventNameregistered on the given emitter.
const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+The emitter to query
+The event name
+v0.9.12
+Since v3.2.0 - Use listenerCount instead.
Static getReturns a copy of the array of listeners for the event named eventName.
For EventEmitters this behaves exactly the same as calling .listeners on
+the emitter.
For EventTargets this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
const { getEventListeners, EventEmitter } = require('events');
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
getEventListeners(ee, 'foo'); // [listener]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
getEventListeners(et, 'foo'); // [listener]
}
+
+v15.2.0, v14.17.0
+Static getReturns the currently set max amount of listeners.
+For EventEmitters this behaves exactly the same as calling .getMaxListeners on
+the emitter.
For EventTargets this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+v18.17.0
+Static setconst {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+Optional n: numberA non-negative number. The maximum number of listeners per EventTarget event.
Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]v15.4.0
+Static addExperimental Listens once to the abort event on the provided signal.
Listening to the abort event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignals in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+Disposable that removes the abort listener.
v18.18.0
+Alias for emitter.removeListener().
Rest ...args: any[]v10.0.0
+Removes all listeners, or those of the specified eventName.
It is bad practice to remove listeners added elsewhere in the code,
+particularly when the EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter, so that calls can be chained.
Optional event: string | symbolv0.1.26
+By default EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter, so that calls can be chained.
v0.3.5
+Returns the current max listener value for the EventEmitter which is either
+set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.
v1.0.0
+Returns a copy of the array of listeners for the event named eventName.
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+
+v0.1.26
+Returns a copy of the array of listeners for the event named eventName,
+including any wrappers (such as those created by .once()).
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
// Returns a new Array with a function `onceWrapper` which has a property
// `listener` which contains the original listener bound above
const listeners = emitter.rawListeners('log');
const logFnWrapper = listeners[0];
// Logs "log once" to the console and does not unbind the `once` event
logFnWrapper.listener();
// Logs "log once" to the console and removes the listener
logFnWrapper();
emitter.on('log', () => console.log('log persistently'));
// Will return a new Array with a single function bound by `.on()` above
const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice
newListeners[0]();
emitter.emit('log');
+
+v9.4.0
+Returns the number of listeners listening to the event named eventName.
If listener is provided, it will return how many times the listener
+is found in the list of the listeners of the event.
The name of the event being listened for
+Optional listener: FunctionThe event handler function
+v3.2.0
+Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbols.
const EventEmitter = require('events');
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+v6.0.0
+Closes writeStream. Optionally accepts a
+callback that will be executed once the writeStreamis closed.
Optional callback: ((err?) => void)Optional err: ErrnoExceptionv0.9.4
+events.EventEmitter
+Rest ...args: any[]Adds the listener function to the end of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple
+times.
server.on('connection', (stream) => {
console.log('someone connected!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. Theemitter.prependListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+The name of the event.
+The callback function
+v0.1.101
+Rest ...args: any[]Adds a one-timelistener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. Theemitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+The name of the event.
+The callback function
+v0.3.0
+Rest ...args: any[]Adds the listener function to the beginning of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple
+times.
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+v6.0.0
+Rest ...args: any[]Adds a one-timelistener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+v6.0.0
+Rest ...args: any[]Optional options: { Optional end?: booleanOptional options: { Static fromExperimental A utility method for creating a Writable from a web WritableStream.
Optional options: Pick<WritableOptions, "highWaterMark" | "objectMode" | "signal" | "decodeStrings">v17.0.0
+Static toExperimental A utility method for creating a web WritableStream from a Writable.
v17.0.0
+Optional error: ErrorOptional _writevOptional error: ErrorOptional _constructThe writable.write() method writes some data to the stream, and calls the
+supplied callback once the data has been fully handled. If an error
+occurs, the callback will be called with the error as its
+first argument. The callback is called asynchronously and before 'error' is
+emitted.
The return value is true if the internal buffer is less than thehighWaterMark configured when the stream was created after admitting chunk.
+If false is returned, further attempts to write data to the stream should
+stop until the 'drain' event is emitted.
While a stream is not draining, calls to write() will buffer chunk, and
+return false. Once all currently buffered chunks are drained (accepted for
+delivery by the operating system), the 'drain' event will be emitted.
+Once write() returns false, do not write more chunks
+until the 'drain' event is emitted. While calling write() on a stream that
+is not draining is allowed, Node.js will buffer all written chunks until
+maximum memory usage occurs, at which point it will abort unconditionally.
+Even before it aborts, high memory usage will cause poor garbage collector
+performance and high RSS (which is not typically released back to the system,
+even after the memory is no longer required). Since TCP sockets may never
+drain if the remote peer does not read the data, writing a socket that is
+not draining may lead to a remotely exploitable vulnerability.
Writing data while the stream is not draining is particularly
+problematic for a Transform, because the Transform streams are paused
+by default until they are piped or a 'data' or 'readable' event handler
+is added.
If the data to be written can be generated or fetched on demand, it is
+recommended to encapsulate the logic into a Readable and use pipe. However, if calling write() is preferred, it is
+possible to respect backpressure and avoid memory issues using the 'drain' event:
function write(data, cb) {
if (!stream.write(data)) {
stream.once('drain', cb);
} else {
process.nextTick(cb);
}
}
// Wait for cb to be called before doing any other write.
write('hello', () => {
console.log('Write completed, do more writes now.');
});
+
+A Writable stream in object mode will always ignore the encoding argument.
Optional data to write. For streams not operating in object mode, chunk must be a string, Buffer or Uint8Array. For object mode streams, chunk may be any
+JavaScript value other than null.
Optional callback: ((error) => void)Callback for when this chunk of data is flushed.
+false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.
v0.9.4
+Optional callback: ((error) => void)The writable.setDefaultEncoding() method sets the default encoding for a Writable stream.
The new default encoding
+v0.11.15
+Calling the writable.end() method signals that no more data will be written
+to the Writable. The optional chunk and encoding arguments allow one
+final additional chunk of data to be written immediately before closing the
+stream.
Calling the write method after calling end will raise an error.
+// Write 'hello, ' and then end with 'world!'.
const fs = require('fs');
const file = fs.createWriteStream('example.txt');
file.write('hello, ');
file.end('world!');
// Writing more now is not allowed!
+
+Optional cb: (() => void)v0.9.4
+Optional cb: (() => void)Optional cb: (() => void)The writable.cork() method forces all written data to be buffered in memory.
+The buffered data will be flushed when either the uncork or end methods are called.
The primary intent of writable.cork() is to accommodate a situation in which
+several small chunks are written to the stream in rapid succession. Instead of
+immediately forwarding them to the underlying destination, writable.cork()buffers all the chunks until writable.uncork() is called, which will pass them
+all to writable._writev(), if present. This prevents a head-of-line blocking
+situation where data is being buffered while waiting for the first small chunk
+to be processed. However, use of writable.cork() without implementingwritable._writev() may have an adverse effect on throughput.
See also: writable.uncork(), writable._writev().
v0.11.2
+The writable.uncork() method flushes all data buffered since cork was called.
When using writable.cork() and writable.uncork() to manage the buffering
+of writes to a stream, defer calls to writable.uncork() usingprocess.nextTick(). Doing so allows batching of allwritable.write() calls that occur within a given Node.js event
+loop phase.
stream.cork();
stream.write('some ');
stream.write('data ');
process.nextTick(() => stream.uncork());
+
+If the writable.cork() method is called multiple times on a stream, the
+same number of calls to writable.uncork() must be called to flush the buffered
+data.
stream.cork();
stream.write('some ');
stream.cork();
stream.write('data ');
process.nextTick(() => {
stream.uncork();
// The data will not be flushed until uncork() is called a second time.
stream.uncork();
});
+
+See also: writable.cork().
v0.11.2
+Destroy the stream. Optionally emit an 'error' event, and emit a 'close'event (unless emitClose is set to false). After this call, the writable
+stream has ended and subsequent calls to write() or end() will result in
+an ERR_STREAM_DESTROYED error.
+This is a destructive and immediate way to destroy a stream. Previous calls towrite() may not have drained, and may trigger an ERR_STREAM_DESTROYED error.
+Use end() instead of destroy if data should flush before close, or wait for
+the 'drain' event before destroying the stream.
Once destroy() has been called any further calls will be a no-op and no
+further errors except from _destroy() may be emitted as 'error'.
Implementors should not override this method,
+but instead implement writable._destroy().
Optional error: ErrorOptional, an error to emit with 'error' event.
v8.0.0
+Synchronously calls each of the listeners registered for the event namedeventName, in the order they were registered, passing the supplied arguments
+to each.
Returns true if the event had listeners, false otherwise.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
+
+v0.1.26
+Rest ...args: any[]Removes the specified listener from the listener array for the event namedeventName.
const callback = (stream) => {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
+
+removeListener() will remove, at most, one instance of a listener from the
+listener array. If any single listener has been added multiple times to the
+listener array for the specified eventName, then removeListener() must be
+called multiple times to remove each instance.
Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that anyremoveListener() or removeAllListeners() calls after emitting and before the last listener finishes execution
+will not remove them fromemit() in progress. Subsequent events behave as expected.
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners() method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener() will remove the most
+recently added instance. In the example the once('ping')listener is removed:
const ee = new EventEmitter();
function pong() {
console.log('pong');
}
ee.on('ping', pong);
ee.once('ping', pong);
ee.removeListener('ping', pong);
ee.emit('ping');
ee.emit('ping');
+
+Returns a reference to the EventEmitter, so that calls can be chained.
v0.1.26
+Rest ...args: any[]Generated using TypeDoc
Encapsulates an X509 certificate and provides read-only access to +its information.
+const { X509Certificate } = await import('crypto');
const x509 = new X509Certificate('{... pem encoded cert ...}');
console.log(x509.subject);
+
+v15.6.0
+Readonly caWill be true if this is a Certificate Authority (CA) certificate.
v15.6.0
+Readonly fingerprintThe SHA-1 fingerprint of this certificate.
+Because SHA-1 is cryptographically broken and because the security of SHA-1 is
+significantly worse than that of algorithms that are commonly used to sign
+certificates, consider using x509.fingerprint256 instead.
v15.6.0
+Readonly fingerprint256The SHA-256 fingerprint of this certificate.
+v15.6.0
+Readonly fingerprint512The SHA-512 fingerprint of this certificate.
+v16.14.0
+Readonly subjectThe complete subject of this certificate.
+v15.6.0
+Readonly subjectThe subject alternative name specified for this certificate or undefined
+if not available.
v15.6.0
+Readonly infoThe information access content of this certificate or undefined if not
+available.
v15.6.0
+Readonly keyAn array detailing the key usages for this certificate.
+v15.6.0
+Readonly issuerThe issuer identification included in this certificate.
+v15.6.0
+Optional Readonly issuerThe issuer certificate or undefined if the issuer certificate is not
+available.
v15.9.0
+Readonly publicThe public key KeyObject for this certificate.
v15.6.0
+Readonly rawA Buffer containing the DER encoding of this certificate.
v15.6.0
+Readonly serialThe serial number of this certificate.
+Serial numbers are assigned by certificate authorities and do not uniquely
+identify certificates. Consider using x509.fingerprint256 as a unique
+identifier instead.
v15.6.0
+Readonly validThe date/time from which this certificate is considered valid.
+v15.6.0
+Readonly validThe date/time until which this certificate is considered valid.
+v15.6.0
+Checks whether the certificate matches the given email address.
+If the 'subject' option is undefined or set to 'default', the certificate
+subject is only considered if the subject alternative name extension either does
+not exist or does not contain any email addresses.
If the 'subject' option is set to 'always' and if the subject alternative
+name extension either does not exist or does not contain a matching email
+address, the certificate subject is considered.
If the 'subject' option is set to 'never', the certificate subject is never
+considered, even if the certificate contains no subject alternative names.
Optional options: Pick<X509CheckOptions, "subject">Returns email if the certificate matches, undefined if it does not.
v15.6.0
+Checks whether the certificate matches the given host name.
+If the certificate matches the given host name, the matching subject name is
+returned. The returned name might be an exact match (e.g., foo.example.com)
+or it might contain wildcards (e.g., *.example.com). Because host name
+comparisons are case-insensitive, the returned subject name might also differ
+from the given name in capitalization.
If the 'subject' option is undefined or set to 'default', the certificate
+subject is only considered if the subject alternative name extension either does
+not exist or does not contain any DNS names. This behavior is consistent with RFC 2818 ("HTTP Over TLS").
If the 'subject' option is set to 'always' and if the subject alternative
+name extension either does not exist or does not contain a matching DNS name,
+the certificate subject is considered.
If the 'subject' option is set to 'never', the certificate subject is never
+considered, even if the certificate contains no subject alternative names.
Optional options: X509CheckOptionsReturns a subject name that matches name, or undefined if no subject name matches name.
v15.6.0
+Checks whether the certificate matches the given IP address (IPv4 or IPv6).
+Only RFC 5280 iPAddress subject alternative names are considered, and they
+must match the given ip address exactly. Other subject alternative names as
+well as the subject field of the certificate are ignored.
Returns ip if the certificate matches, undefined if it does not.
v15.6.0
+Checks whether this certificate was issued by the given otherCert.
v15.6.0
+Checks whether the public key for this certificate is consistent with +the given private key.
+A private key.
+v15.6.0
+Returns information about this certificate using the legacy certificate object encoding.
v15.6.0
+Verifies that this certificate was signed by the given public key. +Does not perform any other validation checks on the certificate.
+A public key.
+v15.6.0
+Generated using TypeDoc
Duplex streams are streams that implement both the Readable and Writable interfaces.
Examples of Duplex streams include:
TCP socketszlib streamscrypto streamsv0.9.4
+Optional opts: DuplexOptionsStatic Readonly errorThis symbol shall be used to install a listener for only monitoring 'error'
+events. Listeners installed using this symbol are called before the regular
+'error' listeners are called.
Installing a listener using this symbol does not change the behavior once an
+'error' event is emitted, therefore the process will still crash if no
+regular 'error' listener is installed.
Static Readonly captureStatic captureSets or gets the default captureRejection value for all emitters.
+Static defaultReadonly Experimental readableReturns whether the stream was destroyed or errored before emitting 'end'.
v16.8.0
+Is true if it is safe to call readable.read(), which means
+the stream has not been destroyed or emitted 'error' or 'end'.
v11.4.0
+Readonly Experimental readableReturns whether 'data' has been emitted.
v16.7.0, v14.18.0
+Readonly readableGetter for the property encoding of a given Readable stream. The encodingproperty can be set using the readable.setEncoding() method.
v12.7.0
+Readonly readableBecomes true when 'end' event is emitted.
v12.9.0
+Readonly readableThis property reflects the current state of a Readable stream as described
+in the Three states section.
v9.4.0
+Readonly readableReturns the value of highWaterMark passed when creating this Readable.
v9.3.0
+Readonly readableThis property contains the number of bytes (or objects) in the queue
+ready to be read. The value provides introspection data regarding
+the status of the highWaterMark.
v9.4.0
+Readonly readableGetter for the property objectMode of a given Readable stream.
v12.3.0
+Is true after readable.destroy() has been called.
v8.0.0
+Readonly writableIs true if it is safe to call writable.write(), which means
+the stream has not been destroyed, errored or ended.
v11.4.0
+Readonly writableIs true after writable.end() has been called. This property
+does not indicate whether the data has been flushed, for this use writable.writableFinished instead.
v12.9.0
+Readonly writableIs set to true immediately before the 'finish' event is emitted.
v12.6.0
+Readonly writableReturn the value of highWaterMark passed when creating this Writable.
v9.3.0
+Readonly writableThis property contains the number of bytes (or objects) in the queue
+ready to be written. The value provides introspection data regarding
+the status of the highWaterMark.
v9.4.0
+Readonly writableGetter for the property objectMode of a given Writable stream.
v12.3.0
+Readonly writableNumber of times writable.uncork() needs to be
+called in order to fully uncork the stream.
v13.2.0, v12.16.0
+Readonly writableIs true if the stream's buffer has been full and stream will emit 'drain'.
v15.2.0, v14.17.0
+Readonly closedIs true after 'close' has been emitted.
+v18.0.0
+Readonly erroredReturns error if the stream has been destroyed with an error.
+v18.0.0
+If false then the stream will automatically end the writable side when the
+readable side ends. Set initially by the allowHalfOpen constructor option,
+which defaults to false.
This can be changed manually to change the half-open behavior of an existingDuplex stream instance, but must be changed before the 'end' event is
+emitted.
v0.9.4
+Optional [captureStatic onceCreates a Promise that is fulfilled when the EventEmitter emits the given
+event or that is rejected if the EventEmitter emits 'error' while waiting.
+The Promise will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error' event
+semantics and does not listen to the 'error' event.
const { once, EventEmitter } = require('events');
async function run() {
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.log('error happened', err);
}
}
run();
+
+The special handling of the 'error' event is only used when events.once()is used to wait for another event. If events.once() is used to wait for the
+'error' event itself, then it is treated as any other kind of event without
+special handling:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.log('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+An AbortSignal can be used to cancel waiting for the event:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+Optional options: StaticEventEmitterOptionsv11.13.0, v10.16.0
+Optional options: StaticEventEmitterOptionsStatic onconst { on, EventEmitter } = require('events');
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
+
+Returns an AsyncIterator that iterates eventName events. It will throw
+if the EventEmitter emits 'error'. It removes all listeners when
+exiting the loop. The value returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal can be used to cancel waiting on events:
const { on, EventEmitter } = require('events');
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+The name of the event being listened for
+Optional options: StaticEventEmitterOptionsthat iterates eventName events emitted by the emitter
v13.6.0, v12.16.0
+Static listenerA class method that returns the number of listeners for the given eventNameregistered on the given emitter.
const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+The emitter to query
+The event name
+v0.9.12
+Since v3.2.0 - Use listenerCount instead.
Static getReturns a copy of the array of listeners for the event named eventName.
For EventEmitters this behaves exactly the same as calling .listeners on
+the emitter.
For EventTargets this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
const { getEventListeners, EventEmitter } = require('events');
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
getEventListeners(ee, 'foo'); // [listener]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
getEventListeners(et, 'foo'); // [listener]
}
+
+v15.2.0, v14.17.0
+Static getReturns the currently set max amount of listeners.
+For EventEmitters this behaves exactly the same as calling .getMaxListeners on
+the emitter.
For EventTargets this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+v18.17.0
+Static setconst {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+Optional n: numberA non-negative number. The maximum number of listeners per EventTarget event.
Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]v15.4.0
+Static addExperimental Listens once to the abort event on the provided signal.
Listening to the abort event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignals in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+Disposable that removes the abort listener.
v18.18.0
+Alias for emitter.removeListener().
Rest ...args: any[]v10.0.0
+Removes all listeners, or those of the specified eventName.
It is bad practice to remove listeners added elsewhere in the code,
+particularly when the EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter, so that calls can be chained.
Optional event: string | symbolv0.1.26
+By default EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter, so that calls can be chained.
v0.3.5
+Returns the current max listener value for the EventEmitter which is either
+set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.
v1.0.0
+Returns a copy of the array of listeners for the event named eventName.
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+
+v0.1.26
+Returns a copy of the array of listeners for the event named eventName,
+including any wrappers (such as those created by .once()).
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
// Returns a new Array with a function `onceWrapper` which has a property
// `listener` which contains the original listener bound above
const listeners = emitter.rawListeners('log');
const logFnWrapper = listeners[0];
// Logs "log once" to the console and does not unbind the `once` event
logFnWrapper.listener();
// Logs "log once" to the console and removes the listener
logFnWrapper();
emitter.on('log', () => console.log('log persistently'));
// Will return a new Array with a single function bound by `.on()` above
const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice
newListeners[0]();
emitter.emit('log');
+
+v9.4.0
+Returns the number of listeners listening to the event named eventName.
If listener is provided, it will return how many times the listener
+is found in the list of the listeners of the event.
The name of the event being listened for
+Optional listener: FunctionThe event handler function
+v3.2.0
+Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbols.
const EventEmitter = require('events');
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+v6.0.0
+Optional options: { Optional end?: booleanOptional options: { Static fromExperimental A utility method for creating a Readable from a web ReadableStream.
Optional options: Pick<ReadableOptions, "encoding" | "highWaterMark" | "objectMode" | "signal">v17.0.0
+Static isReturns whether the stream has been read from or cancelled.
+v16.8.0
+Static toExperimental A utility method for creating a web ReadableStream from a Readable.
v17.0.0
+Optional _constructThe readable.read() method reads data out of the internal buffer and
+returns it. If no data is available to be read, null is returned. By default,
+the data is returned as a Buffer object unless an encoding has been
+specified using the readable.setEncoding() method or the stream is operating
+in object mode.
The optional size argument specifies a specific number of bytes to read. Ifsize bytes are not available to be read, null will be returned _unless_the stream has ended, in which
+case all of the data remaining in the internal
+buffer will be returned.
If the size argument is not specified, all of the data contained in the
+internal buffer will be returned.
The size argument must be less than or equal to 1 GiB.
The readable.read() method should only be called on Readable streams
+operating in paused mode. In flowing mode, readable.read() is called
+automatically until the internal buffer is fully drained.
const readable = getReadableStreamSomehow();
// 'readable' may be triggered multiple times as data is buffered in
readable.on('readable', () => {
let chunk;
console.log('Stream is readable (new data received in buffer)');
// Use a loop to make sure we read all currently available data
while (null !== (chunk = readable.read())) {
console.log(`Read ${chunk.length} bytes of data...`);
}
});
// 'end' will be triggered once when there is no more data available
readable.on('end', () => {
console.log('Reached end of stream.');
});
+
+Each call to readable.read() returns a chunk of data, or null. The chunks
+are not concatenated. A while loop is necessary to consume all data
+currently in the buffer. When reading a large file .read() may return null,
+having consumed all buffered content so far, but there is still more data to
+come not yet buffered. In this case a new 'readable' event will be emitted
+when there is more data in the buffer. Finally the 'end' event will be
+emitted when there is no more data to come.
Therefore to read a file's whole contents from a readable, it is necessary
+to collect chunks across multiple 'readable' events:
const chunks = [];
readable.on('readable', () => {
let chunk;
while (null !== (chunk = readable.read())) {
chunks.push(chunk);
}
});
readable.on('end', () => {
const content = chunks.join('');
});
+
+A Readable stream in object mode will always return a single item from
+a call to readable.read(size), regardless of the value of thesize argument.
If the readable.read() method returns a chunk of data, a 'data' event will
+also be emitted.
Calling read after the 'end' event has
+been emitted will return null. No runtime error will be raised.
Optional size: numberOptional argument to specify how much data to read.
+v0.9.4
+The readable.setEncoding() method sets the character encoding for
+data read from the Readable stream.
By default, no encoding is assigned and stream data will be returned asBuffer objects. Setting an encoding causes the stream data
+to be returned as strings of the specified encoding rather than as Bufferobjects. For instance, calling readable.setEncoding('utf8') will cause the
+output data to be interpreted as UTF-8 data, and passed as strings. Callingreadable.setEncoding('hex') will cause the data to be encoded in hexadecimal
+string format.
The Readable stream will properly handle multi-byte characters delivered
+through the stream that would otherwise become improperly decoded if simply
+pulled from the stream as Buffer objects.
const readable = getReadableStreamSomehow();
readable.setEncoding('utf8');
readable.on('data', (chunk) => {
assert.equal(typeof chunk, 'string');
console.log('Got %d characters of string data:', chunk.length);
});
+
+The encoding to use.
+v0.9.4
+The readable.pause() method will cause a stream in flowing mode to stop
+emitting 'data' events, switching out of flowing mode. Any data that
+becomes available will remain in the internal buffer.
const readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
readable.pause();
console.log('There will be no additional data for 1 second.');
setTimeout(() => {
console.log('Now data will start flowing again.');
readable.resume();
}, 1000);
});
+
+The readable.pause() method has no effect if there is a 'readable'event listener.
v0.9.4
+The readable.resume() method causes an explicitly paused Readable stream to
+resume emitting 'data' events, switching the stream into flowing mode.
The readable.resume() method can be used to fully consume the data from a
+stream without actually processing any of that data:
getReadableStreamSomehow()
.resume()
.on('end', () => {
console.log('Reached the end, but did not read anything.');
});
+
+The readable.resume() method has no effect if there is a 'readable'event listener.
v0.9.4
+The readable.isPaused() method returns the current operating state of theReadable. This is used primarily by the mechanism that underlies thereadable.pipe() method. In most
+typical cases, there will be no reason to
+use this method directly.
const readable = new stream.Readable();
readable.isPaused(); // === false
readable.pause();
readable.isPaused(); // === true
readable.resume();
readable.isPaused(); // === false
+
+v0.11.14
+The readable.unpipe() method detaches a Writable stream previously attached
+using the pipe method.
If the destination is not specified, then all pipes are detached.
If the destination is specified, but no pipe is set up for it, then
+the method does nothing.
const fs = require('fs');
const readable = getReadableStreamSomehow();
const writable = fs.createWriteStream('file.txt');
// All the data from readable goes into 'file.txt',
// but only for the first second.
readable.pipe(writable);
setTimeout(() => {
console.log('Stop writing to file.txt.');
readable.unpipe(writable);
console.log('Manually close the file stream.');
writable.end();
}, 1000);
+
+Optional destination: WritableStreamOptional specific stream to unpipe
+v0.9.4
+Passing chunk as null signals the end of the stream (EOF) and behaves the
+same as readable.push(null), after which no more data can be written. The EOF
+signal is put at the end of the buffer and any buffered data will still be
+flushed.
The readable.unshift() method pushes a chunk of data back into the internal
+buffer. This is useful in certain situations where a stream is being consumed by
+code that needs to "un-consume" some amount of data that it has optimistically
+pulled out of the source, so that the data can be passed on to some other party.
The stream.unshift(chunk) method cannot be called after the 'end' event
+has been emitted or a runtime error will be thrown.
Developers using stream.unshift() often should consider switching to
+use of a Transform stream instead. See the API for stream implementers section for more information.
// Pull off a header delimited by \n\n.
// Use unshift() if we get too much.
// Call the callback with (error, header, stream).
const { StringDecoder } = require('string_decoder');
function parseHeader(stream, callback) {
stream.on('error', callback);
stream.on('readable', onReadable);
const decoder = new StringDecoder('utf8');
let header = '';
function onReadable() {
let chunk;
while (null !== (chunk = stream.read())) {
const str = decoder.write(chunk);
if (str.includes('\n\n')) {
// Found the header boundary.
const split = str.split(/\n\n/);
header += split.shift();
const remaining = split.join('\n\n');
const buf = Buffer.from(remaining, 'utf8');
stream.removeListener('error', callback);
// Remove the 'readable' listener before unshifting.
stream.removeListener('readable', onReadable);
if (buf.length)
stream.unshift(buf);
// Now the body of the message can be read from the stream.
callback(null, header, stream);
return;
}
// Still reading the header.
header += str;
}
}
}
+
+Unlike push, stream.unshift(chunk) will not
+end the reading process by resetting the internal reading state of the stream.
+This can cause unexpected results if readable.unshift() is called during a
+read (i.e. from within a _read implementation on a
+custom stream). Following the call to readable.unshift() with an immediate push will reset the reading state appropriately,
+however it is best to simply avoid calling readable.unshift() while in the
+process of performing a read.
Chunk of data to unshift onto the read queue. For streams not operating in object mode, chunk must be a string, Buffer, Uint8Array or null. For object mode
+streams, chunk may be any JavaScript value.
Optional encoding: BufferEncodingEncoding of string chunks. Must be a valid Buffer encoding, such as 'utf8' or 'ascii'.
v0.9.11
+Prior to Node.js 0.10, streams did not implement the entire stream module API
+as it is currently defined. (See Compatibility for more information.)
When using an older Node.js library that emits 'data' events and has a pause method that is advisory only, thereadable.wrap() method can be used to create a Readable
+stream that uses
+the old stream as its data source.
It will rarely be necessary to use readable.wrap() but the method has been
+provided as a convenience for interacting with older Node.js applications and
+libraries.
const { OldReader } = require('./old-api-module.js');
const { Readable } = require('stream');
const oreader = new OldReader();
const myReader = new Readable().wrap(oreader);
myReader.on('readable', () => {
myReader.read(); // etc.
});
+
+An "old style" readable stream
+v0.9.4
+Optional encoding: BufferEncodingThe iterator created by this method gives users the option to cancel the destruction
+of the stream if the for await...of loop is exited by return, break, or throw,
+or if the iterator should destroy the stream if the stream emitted an error during iteration.
Optional options: { Optional destroyWhen set to false, calling return on the async iterator,
+or exiting a for await...of iteration using a break, return, or throw will not destroy the stream.
+Default: true.
v16.3.0
+This method allows mapping over the stream. The fn function will be called for every chunk in the stream.
+If the fn function returns a promise - that promise will be awaited before being passed to the result stream.
a function to map over every chunk in the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa stream mapped with the function fn.
+v17.4.0, v16.14.0
+This method allows filtering the stream. For each chunk in the stream the fn function will be called
+and if it returns a truthy value, the chunk will be passed to the result stream.
+If the fn function returns a promise - that promise will be awaited.
a function to filter chunks from the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa stream filtered with the predicate fn.
+v17.4.0, v16.14.0
+This method allows iterating a stream. For each chunk in the stream the fn function will be called.
+If the fn function returns a promise - that promise will be awaited.
This method is different from for await...of loops in that it can optionally process chunks concurrently.
+In addition, a forEach iteration can only be stopped by having passed a signal option
+and aborting the related AbortController while for await...of can be stopped with break or return.
+In either case the stream will be destroyed.
This method is different from listening to the 'data' event in that it uses the readable event
+in the underlying machinary and can limit the number of concurrent fn calls.
a function to call on each chunk of the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa promise for when the stream has finished.
+v17.5.0
+This method allows easily obtaining the contents of a stream.
+As this method reads the entire stream into memory, it negates the benefits of streams. It's intended +for interoperability and convenience, not as the primary way to consume streams.
+Optional options: Pick<ArrayOptions, "signal">a promise containing an array with the contents of the stream.
+v17.5.0
+This method is similar to Array.prototype.some and calls fn on each chunk in the stream
+until the awaited return value is true (or any truthy value). Once an fn call on a chunk
+awaited return value is truthy, the stream is destroyed and the promise is fulfilled with true.
+If none of the fn calls on the chunks return a truthy value, the promise is fulfilled with false.
a function to call on each chunk of the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa promise evaluating to true if fn returned a truthy value for at least one of the chunks.
v17.5.0
+This method is similar to Array.prototype.find and calls fn on each chunk in the stream
+to find a chunk with a truthy value for fn. Once an fn call's awaited return value is truthy,
+the stream is destroyed and the promise is fulfilled with value for which fn returned a truthy value.
+If all of the fn calls on the chunks return a falsy value, the promise is fulfilled with undefined.
a function to call on each chunk of the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa promise evaluating to the first chunk for which fn evaluated with a truthy value,
+or undefined if no element was found.
v17.5.0
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsThis method is similar to Array.prototype.every and calls fn on each chunk in the stream
+to check if all awaited return values are truthy value for fn. Once an fn call on a chunk
+awaited return value is falsy, the stream is destroyed and the promise is fulfilled with false.
+If all of the fn calls on the chunks return a truthy value, the promise is fulfilled with true.
a function to call on each chunk of the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa promise evaluating to true if fn returned a truthy value for every one of the chunks.
v17.5.0
+This method returns a new stream by applying the given callback to each chunk of the stream +and then flattening the result.
+It is possible to return a stream or another iterable or async iterable from fn and the result streams +will be merged (flattened) into the returned stream.
+a function to map over every chunk in the stream. May be async. May be a stream or generator.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa stream flat-mapped with the function fn.
+v17.5.0
+This method returns a new stream with the first limit chunks dropped from the start.
+the number of chunks to drop from the readable.
+Optional options: Pick<ArrayOptions, "signal">a stream with limit chunks dropped from the start.
+v17.5.0
+This method returns a new stream with the first limit chunks.
+the number of chunks to take from the readable.
+Optional options: Pick<ArrayOptions, "signal">a stream with limit chunks taken.
+v17.5.0
+This method returns a new stream with chunks of the underlying stream paired with a counter
+in the form [index, chunk]. The first index value is 0 and it increases by 1 for each chunk produced.
Optional options: Pick<ArrayOptions, "signal">a stream of indexed pairs.
+v17.5.0
+This method calls fn on each chunk of the stream in order, passing it the result from the calculation +on the previous element. It returns a promise for the final value of the reduction.
+If no initial value is supplied the first chunk of the stream is used as the initial value.
+If the stream is empty, the promise is rejected with a TypeError with the ERR_INVALID_ARGS code property.
The reducer function iterates the stream element-by-element which means that there is no concurrency parameter
+or parallelism. To perform a reduce concurrently, you can extract the async function to readable.map method.
a reducer function to call over every chunk in the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional initial: undefinedthe initial value to use in the reduction.
+Optional options: Pick<ArrayOptions, "signal">a promise for the final value of the reduction.
+v17.5.0
+Optional options: Pick<ArrayOptions, "signal">Optional options: Pick<ArrayOptions, "signal">Destroy the stream. Optionally emit an 'error' event, and emit a 'close'event (unless emitClose is set to false). After this call, the readable
+stream will release any internal resources and subsequent calls to push()will be ignored.
Once destroy() has been called any further calls will be a no-op and no
+further errors except from _destroy() may be emitted as 'error'.
Implementors should not override this method, but instead implement readable._destroy().
Optional error: ErrorError which will be passed as payload in 'error' event
v8.0.0
+Static fromA utility method for creating duplex streams.
+Stream converts writable stream into writable Duplex and readable stream
+to Duplex.Blob converts into readable Duplex.string converts into readable Duplex.ArrayBuffer converts into readable Duplex.AsyncIterable converts into a readable Duplex. Cannot yield null.AsyncGeneratorFunction converts into a readable/writable transform
+Duplex. Must take a source AsyncIterable as first parameter. Cannot yield
+null.AsyncFunction converts into a writable Duplex. Must return
+either null or undefinedObject ({ writable, readable }) converts readable and
+writable into Stream and then combines them into Duplex where the
+Duplex will write to the writable and read from the readable.Promise converts into readable Duplex. Value null is ignored.v16.8.0
+Optional error: ErrorOptional _writevOptional error: ErrorThe writable.write() method writes some data to the stream, and calls the
+supplied callback once the data has been fully handled. If an error
+occurs, the callback will be called with the error as its
+first argument. The callback is called asynchronously and before 'error' is
+emitted.
The return value is true if the internal buffer is less than thehighWaterMark configured when the stream was created after admitting chunk.
+If false is returned, further attempts to write data to the stream should
+stop until the 'drain' event is emitted.
While a stream is not draining, calls to write() will buffer chunk, and
+return false. Once all currently buffered chunks are drained (accepted for
+delivery by the operating system), the 'drain' event will be emitted.
+Once write() returns false, do not write more chunks
+until the 'drain' event is emitted. While calling write() on a stream that
+is not draining is allowed, Node.js will buffer all written chunks until
+maximum memory usage occurs, at which point it will abort unconditionally.
+Even before it aborts, high memory usage will cause poor garbage collector
+performance and high RSS (which is not typically released back to the system,
+even after the memory is no longer required). Since TCP sockets may never
+drain if the remote peer does not read the data, writing a socket that is
+not draining may lead to a remotely exploitable vulnerability.
Writing data while the stream is not draining is particularly
+problematic for a Transform, because the Transform streams are paused
+by default until they are piped or a 'data' or 'readable' event handler
+is added.
If the data to be written can be generated or fetched on demand, it is
+recommended to encapsulate the logic into a Readable and use pipe. However, if calling write() is preferred, it is
+possible to respect backpressure and avoid memory issues using the 'drain' event:
function write(data, cb) {
if (!stream.write(data)) {
stream.once('drain', cb);
} else {
process.nextTick(cb);
}
}
// Wait for cb to be called before doing any other write.
write('hello', () => {
console.log('Write completed, do more writes now.');
});
+
+A Writable stream in object mode will always ignore the encoding argument.
Optional data to write. For streams not operating in object mode, chunk must be a string, Buffer or Uint8Array. For object mode streams, chunk may be any
+JavaScript value other than null.
Optional encoding: BufferEncodingCallback for when this chunk of data is flushed.
+Optional cb: ((error) => void)false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.
v0.9.4
+Optional cb: ((error) => void)The writable.setDefaultEncoding() method sets the default encoding for a Writable stream.
The new default encoding
+v0.11.15
+Calling the writable.end() method signals that no more data will be written
+to the Writable. The optional chunk and encoding arguments allow one
+final additional chunk of data to be written immediately before closing the
+stream.
Calling the write method after calling end will raise an error.
+// Write 'hello, ' and then end with 'world!'.
const fs = require('fs');
const file = fs.createWriteStream('example.txt');
file.write('hello, ');
file.end('world!');
// Writing more now is not allowed!
+
+Optional cb: (() => void)v0.9.4
+Optional cb: (() => void)Optional encoding: BufferEncodingOptional cb: (() => void)The writable.cork() method forces all written data to be buffered in memory.
+The buffered data will be flushed when either the uncork or end methods are called.
The primary intent of writable.cork() is to accommodate a situation in which
+several small chunks are written to the stream in rapid succession. Instead of
+immediately forwarding them to the underlying destination, writable.cork()buffers all the chunks until writable.uncork() is called, which will pass them
+all to writable._writev(), if present. This prevents a head-of-line blocking
+situation where data is being buffered while waiting for the first small chunk
+to be processed. However, use of writable.cork() without implementingwritable._writev() may have an adverse effect on throughput.
See also: writable.uncork(), writable._writev().
v0.11.2
+The writable.uncork() method flushes all data buffered since cork was called.
When using writable.cork() and writable.uncork() to manage the buffering
+of writes to a stream, defer calls to writable.uncork() usingprocess.nextTick(). Doing so allows batching of allwritable.write() calls that occur within a given Node.js event
+loop phase.
stream.cork();
stream.write('some ');
stream.write('data ');
process.nextTick(() => stream.uncork());
+
+If the writable.cork() method is called multiple times on a stream, the
+same number of calls to writable.uncork() must be called to flush the buffered
+data.
stream.cork();
stream.write('some ');
stream.cork();
stream.write('data ');
process.nextTick(() => {
stream.uncork();
// The data will not be flushed until uncork() is called a second time.
stream.uncork();
});
+
+See also: writable.cork().
v0.11.2
+Event emitter +The defined events on documents including:
+Rest ...args: any[]Synchronously calls each of the listeners registered for the event namedeventName, in the order they were registered, passing the supplied arguments
+to each.
Returns true if the event had listeners, false otherwise.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
+
+v0.1.26
+Rest ...args: any[]Adds the listener function to the end of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple
+times.
server.on('connection', (stream) => {
console.log('someone connected!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. Theemitter.prependListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+The name of the event.
+The callback function
+v0.1.101
+Rest ...args: any[]Adds a one-timelistener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. Theemitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+The name of the event.
+The callback function
+v0.3.0
+Rest ...args: any[]Adds the listener function to the beginning of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple
+times.
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+v6.0.0
+Rest ...args: any[]Adds a one-timelistener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+v6.0.0
+Rest ...args: any[]Removes the specified listener from the listener array for the event namedeventName.
const callback = (stream) => {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
+
+removeListener() will remove, at most, one instance of a listener from the
+listener array. If any single listener has been added multiple times to the
+listener array for the specified eventName, then removeListener() must be
+called multiple times to remove each instance.
Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that anyremoveListener() or removeAllListeners() calls after emitting and before the last listener finishes execution
+will not remove them fromemit() in progress. Subsequent events behave as expected.
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners() method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener() will remove the most
+recently added instance. In the example the once('ping')listener is removed:
const ee = new EventEmitter();
function pong() {
console.log('pong');
}
ee.on('ping', pong);
ee.once('ping', pong);
ee.removeListener('ping', pong);
ee.emit('ping');
ee.emit('ping');
+
+Returns a reference to the EventEmitter, so that calls can be chained.
v0.1.26
+Rest ...args: any[]Generated using TypeDoc
The stream.PassThrough class is a trivial implementation of a Transform stream that simply passes the input bytes across to the output. Its purpose is
+primarily for examples and testing, but there are some use cases wherestream.PassThrough is useful as a building block for novel sorts of streams.
Optional opts: TransformOptionsStatic Readonly errorThis symbol shall be used to install a listener for only monitoring 'error'
+events. Listeners installed using this symbol are called before the regular
+'error' listeners are called.
Installing a listener using this symbol does not change the behavior once an
+'error' event is emitted, therefore the process will still crash if no
+regular 'error' listener is installed.
Static Readonly captureStatic captureSets or gets the default captureRejection value for all emitters.
+Static defaultReadonly Experimental readableReturns whether the stream was destroyed or errored before emitting 'end'.
v16.8.0
+Is true if it is safe to call readable.read(), which means
+the stream has not been destroyed or emitted 'error' or 'end'.
v11.4.0
+Readonly Experimental readableReturns whether 'data' has been emitted.
v16.7.0, v14.18.0
+Readonly readableGetter for the property encoding of a given Readable stream. The encodingproperty can be set using the readable.setEncoding() method.
v12.7.0
+Readonly readableBecomes true when 'end' event is emitted.
v12.9.0
+Readonly readableThis property reflects the current state of a Readable stream as described
+in the Three states section.
v9.4.0
+Readonly readableReturns the value of highWaterMark passed when creating this Readable.
v9.3.0
+Readonly readableThis property contains the number of bytes (or objects) in the queue
+ready to be read. The value provides introspection data regarding
+the status of the highWaterMark.
v9.4.0
+Readonly readableGetter for the property objectMode of a given Readable stream.
v12.3.0
+Is true after readable.destroy() has been called.
v8.0.0
+Readonly writableIs true if it is safe to call writable.write(), which means
+the stream has not been destroyed, errored or ended.
v11.4.0
+Readonly writableIs true after writable.end() has been called. This property
+does not indicate whether the data has been flushed, for this use writable.writableFinished instead.
v12.9.0
+Readonly writableIs set to true immediately before the 'finish' event is emitted.
v12.6.0
+Readonly writableReturn the value of highWaterMark passed when creating this Writable.
v9.3.0
+Readonly writableThis property contains the number of bytes (or objects) in the queue
+ready to be written. The value provides introspection data regarding
+the status of the highWaterMark.
v9.4.0
+Readonly writableGetter for the property objectMode of a given Writable stream.
v12.3.0
+Readonly writableNumber of times writable.uncork() needs to be
+called in order to fully uncork the stream.
v13.2.0, v12.16.0
+Readonly writableIs true if the stream's buffer has been full and stream will emit 'drain'.
v15.2.0, v14.17.0
+Readonly closedIs true after 'close' has been emitted.
+v18.0.0
+Readonly erroredReturns error if the stream has been destroyed with an error.
+v18.0.0
+If false then the stream will automatically end the writable side when the
+readable side ends. Set initially by the allowHalfOpen constructor option,
+which defaults to false.
This can be changed manually to change the half-open behavior of an existingDuplex stream instance, but must be changed before the 'end' event is
+emitted.
v0.9.4
+Optional [captureStatic onceCreates a Promise that is fulfilled when the EventEmitter emits the given
+event or that is rejected if the EventEmitter emits 'error' while waiting.
+The Promise will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error' event
+semantics and does not listen to the 'error' event.
const { once, EventEmitter } = require('events');
async function run() {
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.log('error happened', err);
}
}
run();
+
+The special handling of the 'error' event is only used when events.once()is used to wait for another event. If events.once() is used to wait for the
+'error' event itself, then it is treated as any other kind of event without
+special handling:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.log('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+An AbortSignal can be used to cancel waiting for the event:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+Optional options: StaticEventEmitterOptionsv11.13.0, v10.16.0
+Optional options: StaticEventEmitterOptionsStatic onconst { on, EventEmitter } = require('events');
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
+
+Returns an AsyncIterator that iterates eventName events. It will throw
+if the EventEmitter emits 'error'. It removes all listeners when
+exiting the loop. The value returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal can be used to cancel waiting on events:
const { on, EventEmitter } = require('events');
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+The name of the event being listened for
+Optional options: StaticEventEmitterOptionsthat iterates eventName events emitted by the emitter
v13.6.0, v12.16.0
+Static listenerA class method that returns the number of listeners for the given eventNameregistered on the given emitter.
const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+The emitter to query
+The event name
+v0.9.12
+Since v3.2.0 - Use listenerCount instead.
Static getReturns a copy of the array of listeners for the event named eventName.
For EventEmitters this behaves exactly the same as calling .listeners on
+the emitter.
For EventTargets this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
const { getEventListeners, EventEmitter } = require('events');
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
getEventListeners(ee, 'foo'); // [listener]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
getEventListeners(et, 'foo'); // [listener]
}
+
+v15.2.0, v14.17.0
+Static getReturns the currently set max amount of listeners.
+For EventEmitters this behaves exactly the same as calling .getMaxListeners on
+the emitter.
For EventTargets this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+v18.17.0
+Static setconst {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+Optional n: numberA non-negative number. The maximum number of listeners per EventTarget event.
Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]v15.4.0
+Static addExperimental Listens once to the abort event on the provided signal.
Listening to the abort event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignals in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+Disposable that removes the abort listener.
v18.18.0
+Alias for emitter.removeListener().
Rest ...args: any[]v10.0.0
+Removes all listeners, or those of the specified eventName.
It is bad practice to remove listeners added elsewhere in the code,
+particularly when the EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter, so that calls can be chained.
Optional event: string | symbolv0.1.26
+By default EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter, so that calls can be chained.
v0.3.5
+Returns the current max listener value for the EventEmitter which is either
+set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.
v1.0.0
+Returns a copy of the array of listeners for the event named eventName.
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+
+v0.1.26
+Returns a copy of the array of listeners for the event named eventName,
+including any wrappers (such as those created by .once()).
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
// Returns a new Array with a function `onceWrapper` which has a property
// `listener` which contains the original listener bound above
const listeners = emitter.rawListeners('log');
const logFnWrapper = listeners[0];
// Logs "log once" to the console and does not unbind the `once` event
logFnWrapper.listener();
// Logs "log once" to the console and removes the listener
logFnWrapper();
emitter.on('log', () => console.log('log persistently'));
// Will return a new Array with a single function bound by `.on()` above
const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice
newListeners[0]();
emitter.emit('log');
+
+v9.4.0
+Returns the number of listeners listening to the event named eventName.
If listener is provided, it will return how many times the listener
+is found in the list of the listeners of the event.
The name of the event being listened for
+Optional listener: FunctionThe event handler function
+v3.2.0
+Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbols.
const EventEmitter = require('events');
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+v6.0.0
+Optional options: { Optional end?: booleanOptional options: { Static fromExperimental A utility method for creating a Readable from a web ReadableStream.
Optional options: Pick<ReadableOptions, "encoding" | "highWaterMark" | "objectMode" | "signal">v17.0.0
+Static isReturns whether the stream has been read from or cancelled.
+v16.8.0
+Static toExperimental A utility method for creating a web ReadableStream from a Readable.
v17.0.0
+Optional _constructThe readable.read() method reads data out of the internal buffer and
+returns it. If no data is available to be read, null is returned. By default,
+the data is returned as a Buffer object unless an encoding has been
+specified using the readable.setEncoding() method or the stream is operating
+in object mode.
The optional size argument specifies a specific number of bytes to read. Ifsize bytes are not available to be read, null will be returned _unless_the stream has ended, in which
+case all of the data remaining in the internal
+buffer will be returned.
If the size argument is not specified, all of the data contained in the
+internal buffer will be returned.
The size argument must be less than or equal to 1 GiB.
The readable.read() method should only be called on Readable streams
+operating in paused mode. In flowing mode, readable.read() is called
+automatically until the internal buffer is fully drained.
const readable = getReadableStreamSomehow();
// 'readable' may be triggered multiple times as data is buffered in
readable.on('readable', () => {
let chunk;
console.log('Stream is readable (new data received in buffer)');
// Use a loop to make sure we read all currently available data
while (null !== (chunk = readable.read())) {
console.log(`Read ${chunk.length} bytes of data...`);
}
});
// 'end' will be triggered once when there is no more data available
readable.on('end', () => {
console.log('Reached end of stream.');
});
+
+Each call to readable.read() returns a chunk of data, or null. The chunks
+are not concatenated. A while loop is necessary to consume all data
+currently in the buffer. When reading a large file .read() may return null,
+having consumed all buffered content so far, but there is still more data to
+come not yet buffered. In this case a new 'readable' event will be emitted
+when there is more data in the buffer. Finally the 'end' event will be
+emitted when there is no more data to come.
Therefore to read a file's whole contents from a readable, it is necessary
+to collect chunks across multiple 'readable' events:
const chunks = [];
readable.on('readable', () => {
let chunk;
while (null !== (chunk = readable.read())) {
chunks.push(chunk);
}
});
readable.on('end', () => {
const content = chunks.join('');
});
+
+A Readable stream in object mode will always return a single item from
+a call to readable.read(size), regardless of the value of thesize argument.
If the readable.read() method returns a chunk of data, a 'data' event will
+also be emitted.
Calling read after the 'end' event has
+been emitted will return null. No runtime error will be raised.
Optional size: numberOptional argument to specify how much data to read.
+v0.9.4
+The readable.setEncoding() method sets the character encoding for
+data read from the Readable stream.
By default, no encoding is assigned and stream data will be returned asBuffer objects. Setting an encoding causes the stream data
+to be returned as strings of the specified encoding rather than as Bufferobjects. For instance, calling readable.setEncoding('utf8') will cause the
+output data to be interpreted as UTF-8 data, and passed as strings. Callingreadable.setEncoding('hex') will cause the data to be encoded in hexadecimal
+string format.
The Readable stream will properly handle multi-byte characters delivered
+through the stream that would otherwise become improperly decoded if simply
+pulled from the stream as Buffer objects.
const readable = getReadableStreamSomehow();
readable.setEncoding('utf8');
readable.on('data', (chunk) => {
assert.equal(typeof chunk, 'string');
console.log('Got %d characters of string data:', chunk.length);
});
+
+The encoding to use.
+v0.9.4
+The readable.pause() method will cause a stream in flowing mode to stop
+emitting 'data' events, switching out of flowing mode. Any data that
+becomes available will remain in the internal buffer.
const readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
readable.pause();
console.log('There will be no additional data for 1 second.');
setTimeout(() => {
console.log('Now data will start flowing again.');
readable.resume();
}, 1000);
});
+
+The readable.pause() method has no effect if there is a 'readable'event listener.
v0.9.4
+The readable.resume() method causes an explicitly paused Readable stream to
+resume emitting 'data' events, switching the stream into flowing mode.
The readable.resume() method can be used to fully consume the data from a
+stream without actually processing any of that data:
getReadableStreamSomehow()
.resume()
.on('end', () => {
console.log('Reached the end, but did not read anything.');
});
+
+The readable.resume() method has no effect if there is a 'readable'event listener.
v0.9.4
+The readable.isPaused() method returns the current operating state of theReadable. This is used primarily by the mechanism that underlies thereadable.pipe() method. In most
+typical cases, there will be no reason to
+use this method directly.
const readable = new stream.Readable();
readable.isPaused(); // === false
readable.pause();
readable.isPaused(); // === true
readable.resume();
readable.isPaused(); // === false
+
+v0.11.14
+The readable.unpipe() method detaches a Writable stream previously attached
+using the pipe method.
If the destination is not specified, then all pipes are detached.
If the destination is specified, but no pipe is set up for it, then
+the method does nothing.
const fs = require('fs');
const readable = getReadableStreamSomehow();
const writable = fs.createWriteStream('file.txt');
// All the data from readable goes into 'file.txt',
// but only for the first second.
readable.pipe(writable);
setTimeout(() => {
console.log('Stop writing to file.txt.');
readable.unpipe(writable);
console.log('Manually close the file stream.');
writable.end();
}, 1000);
+
+Optional destination: WritableStreamOptional specific stream to unpipe
+v0.9.4
+Passing chunk as null signals the end of the stream (EOF) and behaves the
+same as readable.push(null), after which no more data can be written. The EOF
+signal is put at the end of the buffer and any buffered data will still be
+flushed.
The readable.unshift() method pushes a chunk of data back into the internal
+buffer. This is useful in certain situations where a stream is being consumed by
+code that needs to "un-consume" some amount of data that it has optimistically
+pulled out of the source, so that the data can be passed on to some other party.
The stream.unshift(chunk) method cannot be called after the 'end' event
+has been emitted or a runtime error will be thrown.
Developers using stream.unshift() often should consider switching to
+use of a Transform stream instead. See the API for stream implementers section for more information.
// Pull off a header delimited by \n\n.
// Use unshift() if we get too much.
// Call the callback with (error, header, stream).
const { StringDecoder } = require('string_decoder');
function parseHeader(stream, callback) {
stream.on('error', callback);
stream.on('readable', onReadable);
const decoder = new StringDecoder('utf8');
let header = '';
function onReadable() {
let chunk;
while (null !== (chunk = stream.read())) {
const str = decoder.write(chunk);
if (str.includes('\n\n')) {
// Found the header boundary.
const split = str.split(/\n\n/);
header += split.shift();
const remaining = split.join('\n\n');
const buf = Buffer.from(remaining, 'utf8');
stream.removeListener('error', callback);
// Remove the 'readable' listener before unshifting.
stream.removeListener('readable', onReadable);
if (buf.length)
stream.unshift(buf);
// Now the body of the message can be read from the stream.
callback(null, header, stream);
return;
}
// Still reading the header.
header += str;
}
}
}
+
+Unlike push, stream.unshift(chunk) will not
+end the reading process by resetting the internal reading state of the stream.
+This can cause unexpected results if readable.unshift() is called during a
+read (i.e. from within a _read implementation on a
+custom stream). Following the call to readable.unshift() with an immediate push will reset the reading state appropriately,
+however it is best to simply avoid calling readable.unshift() while in the
+process of performing a read.
Chunk of data to unshift onto the read queue. For streams not operating in object mode, chunk must be a string, Buffer, Uint8Array or null. For object mode
+streams, chunk may be any JavaScript value.
Optional encoding: BufferEncodingEncoding of string chunks. Must be a valid Buffer encoding, such as 'utf8' or 'ascii'.
v0.9.11
+Prior to Node.js 0.10, streams did not implement the entire stream module API
+as it is currently defined. (See Compatibility for more information.)
When using an older Node.js library that emits 'data' events and has a pause method that is advisory only, thereadable.wrap() method can be used to create a Readable
+stream that uses
+the old stream as its data source.
It will rarely be necessary to use readable.wrap() but the method has been
+provided as a convenience for interacting with older Node.js applications and
+libraries.
const { OldReader } = require('./old-api-module.js');
const { Readable } = require('stream');
const oreader = new OldReader();
const myReader = new Readable().wrap(oreader);
myReader.on('readable', () => {
myReader.read(); // etc.
});
+
+An "old style" readable stream
+v0.9.4
+Optional encoding: BufferEncodingThe iterator created by this method gives users the option to cancel the destruction
+of the stream if the for await...of loop is exited by return, break, or throw,
+or if the iterator should destroy the stream if the stream emitted an error during iteration.
Optional options: { Optional destroyWhen set to false, calling return on the async iterator,
+or exiting a for await...of iteration using a break, return, or throw will not destroy the stream.
+Default: true.
v16.3.0
+This method allows mapping over the stream. The fn function will be called for every chunk in the stream.
+If the fn function returns a promise - that promise will be awaited before being passed to the result stream.
a function to map over every chunk in the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa stream mapped with the function fn.
+v17.4.0, v16.14.0
+This method allows filtering the stream. For each chunk in the stream the fn function will be called
+and if it returns a truthy value, the chunk will be passed to the result stream.
+If the fn function returns a promise - that promise will be awaited.
a function to filter chunks from the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa stream filtered with the predicate fn.
+v17.4.0, v16.14.0
+This method allows iterating a stream. For each chunk in the stream the fn function will be called.
+If the fn function returns a promise - that promise will be awaited.
This method is different from for await...of loops in that it can optionally process chunks concurrently.
+In addition, a forEach iteration can only be stopped by having passed a signal option
+and aborting the related AbortController while for await...of can be stopped with break or return.
+In either case the stream will be destroyed.
This method is different from listening to the 'data' event in that it uses the readable event
+in the underlying machinary and can limit the number of concurrent fn calls.
a function to call on each chunk of the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa promise for when the stream has finished.
+v17.5.0
+This method allows easily obtaining the contents of a stream.
+As this method reads the entire stream into memory, it negates the benefits of streams. It's intended +for interoperability and convenience, not as the primary way to consume streams.
+Optional options: Pick<ArrayOptions, "signal">a promise containing an array with the contents of the stream.
+v17.5.0
+This method is similar to Array.prototype.some and calls fn on each chunk in the stream
+until the awaited return value is true (or any truthy value). Once an fn call on a chunk
+awaited return value is truthy, the stream is destroyed and the promise is fulfilled with true.
+If none of the fn calls on the chunks return a truthy value, the promise is fulfilled with false.
a function to call on each chunk of the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa promise evaluating to true if fn returned a truthy value for at least one of the chunks.
v17.5.0
+This method is similar to Array.prototype.find and calls fn on each chunk in the stream
+to find a chunk with a truthy value for fn. Once an fn call's awaited return value is truthy,
+the stream is destroyed and the promise is fulfilled with value for which fn returned a truthy value.
+If all of the fn calls on the chunks return a falsy value, the promise is fulfilled with undefined.
a function to call on each chunk of the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa promise evaluating to the first chunk for which fn evaluated with a truthy value,
+or undefined if no element was found.
v17.5.0
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsThis method is similar to Array.prototype.every and calls fn on each chunk in the stream
+to check if all awaited return values are truthy value for fn. Once an fn call on a chunk
+awaited return value is falsy, the stream is destroyed and the promise is fulfilled with false.
+If all of the fn calls on the chunks return a truthy value, the promise is fulfilled with true.
a function to call on each chunk of the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa promise evaluating to true if fn returned a truthy value for every one of the chunks.
v17.5.0
+This method returns a new stream by applying the given callback to each chunk of the stream +and then flattening the result.
+It is possible to return a stream or another iterable or async iterable from fn and the result streams +will be merged (flattened) into the returned stream.
+a function to map over every chunk in the stream. May be async. May be a stream or generator.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa stream flat-mapped with the function fn.
+v17.5.0
+This method returns a new stream with the first limit chunks dropped from the start.
+the number of chunks to drop from the readable.
+Optional options: Pick<ArrayOptions, "signal">a stream with limit chunks dropped from the start.
+v17.5.0
+This method returns a new stream with the first limit chunks.
+the number of chunks to take from the readable.
+Optional options: Pick<ArrayOptions, "signal">a stream with limit chunks taken.
+v17.5.0
+This method returns a new stream with chunks of the underlying stream paired with a counter
+in the form [index, chunk]. The first index value is 0 and it increases by 1 for each chunk produced.
Optional options: Pick<ArrayOptions, "signal">a stream of indexed pairs.
+v17.5.0
+This method calls fn on each chunk of the stream in order, passing it the result from the calculation +on the previous element. It returns a promise for the final value of the reduction.
+If no initial value is supplied the first chunk of the stream is used as the initial value.
+If the stream is empty, the promise is rejected with a TypeError with the ERR_INVALID_ARGS code property.
The reducer function iterates the stream element-by-element which means that there is no concurrency parameter
+or parallelism. To perform a reduce concurrently, you can extract the async function to readable.map method.
a reducer function to call over every chunk in the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional initial: undefinedthe initial value to use in the reduction.
+Optional options: Pick<ArrayOptions, "signal">a promise for the final value of the reduction.
+v17.5.0
+Optional options: Pick<ArrayOptions, "signal">Optional options: Pick<ArrayOptions, "signal">Destroy the stream. Optionally emit an 'error' event, and emit a 'close'event (unless emitClose is set to false). After this call, the readable
+stream will release any internal resources and subsequent calls to push()will be ignored.
Once destroy() has been called any further calls will be a no-op and no
+further errors except from _destroy() may be emitted as 'error'.
Implementors should not override this method, but instead implement readable._destroy().
Optional error: ErrorError which will be passed as payload in 'error' event
v8.0.0
+Static fromA utility method for creating duplex streams.
+Stream converts writable stream into writable Duplex and readable stream
+to Duplex.Blob converts into readable Duplex.string converts into readable Duplex.ArrayBuffer converts into readable Duplex.AsyncIterable converts into a readable Duplex. Cannot yield null.AsyncGeneratorFunction converts into a readable/writable transform
+Duplex. Must take a source AsyncIterable as first parameter. Cannot yield
+null.AsyncFunction converts into a writable Duplex. Must return
+either null or undefinedObject ({ writable, readable }) converts readable and
+writable into Stream and then combines them into Duplex where the
+Duplex will write to the writable and read from the readable.Promise converts into readable Duplex. Value null is ignored.v16.8.0
+Optional error: ErrorOptional _writevOptional error: ErrorThe writable.write() method writes some data to the stream, and calls the
+supplied callback once the data has been fully handled. If an error
+occurs, the callback will be called with the error as its
+first argument. The callback is called asynchronously and before 'error' is
+emitted.
The return value is true if the internal buffer is less than thehighWaterMark configured when the stream was created after admitting chunk.
+If false is returned, further attempts to write data to the stream should
+stop until the 'drain' event is emitted.
While a stream is not draining, calls to write() will buffer chunk, and
+return false. Once all currently buffered chunks are drained (accepted for
+delivery by the operating system), the 'drain' event will be emitted.
+Once write() returns false, do not write more chunks
+until the 'drain' event is emitted. While calling write() on a stream that
+is not draining is allowed, Node.js will buffer all written chunks until
+maximum memory usage occurs, at which point it will abort unconditionally.
+Even before it aborts, high memory usage will cause poor garbage collector
+performance and high RSS (which is not typically released back to the system,
+even after the memory is no longer required). Since TCP sockets may never
+drain if the remote peer does not read the data, writing a socket that is
+not draining may lead to a remotely exploitable vulnerability.
Writing data while the stream is not draining is particularly
+problematic for a Transform, because the Transform streams are paused
+by default until they are piped or a 'data' or 'readable' event handler
+is added.
If the data to be written can be generated or fetched on demand, it is
+recommended to encapsulate the logic into a Readable and use pipe. However, if calling write() is preferred, it is
+possible to respect backpressure and avoid memory issues using the 'drain' event:
function write(data, cb) {
if (!stream.write(data)) {
stream.once('drain', cb);
} else {
process.nextTick(cb);
}
}
// Wait for cb to be called before doing any other write.
write('hello', () => {
console.log('Write completed, do more writes now.');
});
+
+A Writable stream in object mode will always ignore the encoding argument.
Optional data to write. For streams not operating in object mode, chunk must be a string, Buffer or Uint8Array. For object mode streams, chunk may be any
+JavaScript value other than null.
Optional encoding: BufferEncodingCallback for when this chunk of data is flushed.
+Optional cb: ((error) => void)false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.
v0.9.4
+Optional cb: ((error) => void)The writable.setDefaultEncoding() method sets the default encoding for a Writable stream.
The new default encoding
+v0.11.15
+Calling the writable.end() method signals that no more data will be written
+to the Writable. The optional chunk and encoding arguments allow one
+final additional chunk of data to be written immediately before closing the
+stream.
Calling the write method after calling end will raise an error.
+// Write 'hello, ' and then end with 'world!'.
const fs = require('fs');
const file = fs.createWriteStream('example.txt');
file.write('hello, ');
file.end('world!');
// Writing more now is not allowed!
+
+Optional cb: (() => void)v0.9.4
+Optional cb: (() => void)Optional encoding: BufferEncodingOptional cb: (() => void)The writable.cork() method forces all written data to be buffered in memory.
+The buffered data will be flushed when either the uncork or end methods are called.
The primary intent of writable.cork() is to accommodate a situation in which
+several small chunks are written to the stream in rapid succession. Instead of
+immediately forwarding them to the underlying destination, writable.cork()buffers all the chunks until writable.uncork() is called, which will pass them
+all to writable._writev(), if present. This prevents a head-of-line blocking
+situation where data is being buffered while waiting for the first small chunk
+to be processed. However, use of writable.cork() without implementingwritable._writev() may have an adverse effect on throughput.
See also: writable.uncork(), writable._writev().
v0.11.2
+The writable.uncork() method flushes all data buffered since cork was called.
When using writable.cork() and writable.uncork() to manage the buffering
+of writes to a stream, defer calls to writable.uncork() usingprocess.nextTick(). Doing so allows batching of allwritable.write() calls that occur within a given Node.js event
+loop phase.
stream.cork();
stream.write('some ');
stream.write('data ');
process.nextTick(() => stream.uncork());
+
+If the writable.cork() method is called multiple times on a stream, the
+same number of calls to writable.uncork() must be called to flush the buffered
+data.
stream.cork();
stream.write('some ');
stream.cork();
stream.write('data ');
process.nextTick(() => {
stream.uncork();
// The data will not be flushed until uncork() is called a second time.
stream.uncork();
});
+
+See also: writable.cork().
v0.11.2
+Event emitter +The defined events on documents including:
+Rest ...args: any[]Synchronously calls each of the listeners registered for the event namedeventName, in the order they were registered, passing the supplied arguments
+to each.
Returns true if the event had listeners, false otherwise.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
+
+v0.1.26
+Rest ...args: any[]Adds the listener function to the end of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple
+times.
server.on('connection', (stream) => {
console.log('someone connected!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. Theemitter.prependListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+The name of the event.
+The callback function
+v0.1.101
+Rest ...args: any[]Adds a one-timelistener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. Theemitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+The name of the event.
+The callback function
+v0.3.0
+Rest ...args: any[]Adds the listener function to the beginning of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple
+times.
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+v6.0.0
+Rest ...args: any[]Adds a one-timelistener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+v6.0.0
+Rest ...args: any[]Removes the specified listener from the listener array for the event namedeventName.
const callback = (stream) => {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
+
+removeListener() will remove, at most, one instance of a listener from the
+listener array. If any single listener has been added multiple times to the
+listener array for the specified eventName, then removeListener() must be
+called multiple times to remove each instance.
Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that anyremoveListener() or removeAllListeners() calls after emitting and before the last listener finishes execution
+will not remove them fromemit() in progress. Subsequent events behave as expected.
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners() method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener() will remove the most
+recently added instance. In the example the once('ping')listener is removed:
const ee = new EventEmitter();
function pong() {
console.log('pong');
}
ee.on('ping', pong);
ee.once('ping', pong);
ee.removeListener('ping', pong);
ee.emit('ping');
ee.emit('ping');
+
+Returns a reference to the EventEmitter, so that calls can be chained.
v0.1.26
+Rest ...args: any[]Generated using TypeDoc
Transform streams are Duplex streams where the output is in some way
+related to the input. Like all Duplex streams, Transform streams
+implement both the Readable and Writable interfaces.
Examples of Transform streams include:
zlib streamscrypto streamsv0.9.4
+Optional opts: TransformOptionsStatic Readonly errorThis symbol shall be used to install a listener for only monitoring 'error'
+events. Listeners installed using this symbol are called before the regular
+'error' listeners are called.
Installing a listener using this symbol does not change the behavior once an
+'error' event is emitted, therefore the process will still crash if no
+regular 'error' listener is installed.
Static Readonly captureStatic captureSets or gets the default captureRejection value for all emitters.
+Static defaultReadonly Experimental readableReturns whether the stream was destroyed or errored before emitting 'end'.
v16.8.0
+Is true if it is safe to call readable.read(), which means
+the stream has not been destroyed or emitted 'error' or 'end'.
v11.4.0
+Readonly Experimental readableReturns whether 'data' has been emitted.
v16.7.0, v14.18.0
+Readonly readableGetter for the property encoding of a given Readable stream. The encodingproperty can be set using the readable.setEncoding() method.
v12.7.0
+Readonly readableBecomes true when 'end' event is emitted.
v12.9.0
+Readonly readableThis property reflects the current state of a Readable stream as described
+in the Three states section.
v9.4.0
+Readonly readableReturns the value of highWaterMark passed when creating this Readable.
v9.3.0
+Readonly readableThis property contains the number of bytes (or objects) in the queue
+ready to be read. The value provides introspection data regarding
+the status of the highWaterMark.
v9.4.0
+Readonly readableGetter for the property objectMode of a given Readable stream.
v12.3.0
+Is true after readable.destroy() has been called.
v8.0.0
+Readonly writableIs true if it is safe to call writable.write(), which means
+the stream has not been destroyed, errored or ended.
v11.4.0
+Readonly writableIs true after writable.end() has been called. This property
+does not indicate whether the data has been flushed, for this use writable.writableFinished instead.
v12.9.0
+Readonly writableIs set to true immediately before the 'finish' event is emitted.
v12.6.0
+Readonly writableReturn the value of highWaterMark passed when creating this Writable.
v9.3.0
+Readonly writableThis property contains the number of bytes (or objects) in the queue
+ready to be written. The value provides introspection data regarding
+the status of the highWaterMark.
v9.4.0
+Readonly writableGetter for the property objectMode of a given Writable stream.
v12.3.0
+Readonly writableNumber of times writable.uncork() needs to be
+called in order to fully uncork the stream.
v13.2.0, v12.16.0
+Readonly writableIs true if the stream's buffer has been full and stream will emit 'drain'.
v15.2.0, v14.17.0
+Readonly closedIs true after 'close' has been emitted.
+v18.0.0
+Readonly erroredReturns error if the stream has been destroyed with an error.
+v18.0.0
+If false then the stream will automatically end the writable side when the
+readable side ends. Set initially by the allowHalfOpen constructor option,
+which defaults to false.
This can be changed manually to change the half-open behavior of an existingDuplex stream instance, but must be changed before the 'end' event is
+emitted.
v0.9.4
+Optional [captureStatic onceCreates a Promise that is fulfilled when the EventEmitter emits the given
+event or that is rejected if the EventEmitter emits 'error' while waiting.
+The Promise will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error' event
+semantics and does not listen to the 'error' event.
const { once, EventEmitter } = require('events');
async function run() {
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.log('error happened', err);
}
}
run();
+
+The special handling of the 'error' event is only used when events.once()is used to wait for another event. If events.once() is used to wait for the
+'error' event itself, then it is treated as any other kind of event without
+special handling:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.log('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+An AbortSignal can be used to cancel waiting for the event:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+Optional options: StaticEventEmitterOptionsv11.13.0, v10.16.0
+Optional options: StaticEventEmitterOptionsStatic onconst { on, EventEmitter } = require('events');
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
+
+Returns an AsyncIterator that iterates eventName events. It will throw
+if the EventEmitter emits 'error'. It removes all listeners when
+exiting the loop. The value returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal can be used to cancel waiting on events:
const { on, EventEmitter } = require('events');
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+The name of the event being listened for
+Optional options: StaticEventEmitterOptionsthat iterates eventName events emitted by the emitter
v13.6.0, v12.16.0
+Static listenerA class method that returns the number of listeners for the given eventNameregistered on the given emitter.
const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+The emitter to query
+The event name
+v0.9.12
+Since v3.2.0 - Use listenerCount instead.
Static getReturns a copy of the array of listeners for the event named eventName.
For EventEmitters this behaves exactly the same as calling .listeners on
+the emitter.
For EventTargets this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
const { getEventListeners, EventEmitter } = require('events');
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
getEventListeners(ee, 'foo'); // [listener]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
getEventListeners(et, 'foo'); // [listener]
}
+
+v15.2.0, v14.17.0
+Static getReturns the currently set max amount of listeners.
+For EventEmitters this behaves exactly the same as calling .getMaxListeners on
+the emitter.
For EventTargets this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+v18.17.0
+Static setconst {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+Optional n: numberA non-negative number. The maximum number of listeners per EventTarget event.
Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]v15.4.0
+Static addExperimental Listens once to the abort event on the provided signal.
Listening to the abort event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignals in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+Disposable that removes the abort listener.
v18.18.0
+Alias for emitter.removeListener().
Rest ...args: any[]v10.0.0
+Removes all listeners, or those of the specified eventName.
It is bad practice to remove listeners added elsewhere in the code,
+particularly when the EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter, so that calls can be chained.
Optional event: string | symbolv0.1.26
+By default EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter, so that calls can be chained.
v0.3.5
+Returns the current max listener value for the EventEmitter which is either
+set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.
v1.0.0
+Returns a copy of the array of listeners for the event named eventName.
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+
+v0.1.26
+Returns a copy of the array of listeners for the event named eventName,
+including any wrappers (such as those created by .once()).
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
// Returns a new Array with a function `onceWrapper` which has a property
// `listener` which contains the original listener bound above
const listeners = emitter.rawListeners('log');
const logFnWrapper = listeners[0];
// Logs "log once" to the console and does not unbind the `once` event
logFnWrapper.listener();
// Logs "log once" to the console and removes the listener
logFnWrapper();
emitter.on('log', () => console.log('log persistently'));
// Will return a new Array with a single function bound by `.on()` above
const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice
newListeners[0]();
emitter.emit('log');
+
+v9.4.0
+Returns the number of listeners listening to the event named eventName.
If listener is provided, it will return how many times the listener
+is found in the list of the listeners of the event.
The name of the event being listened for
+Optional listener: FunctionThe event handler function
+v3.2.0
+Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbols.
const EventEmitter = require('events');
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+v6.0.0
+Optional options: { Optional end?: booleanOptional options: { Static fromExperimental A utility method for creating a Readable from a web ReadableStream.
Optional options: Pick<ReadableOptions, "encoding" | "highWaterMark" | "objectMode" | "signal">v17.0.0
+Static isReturns whether the stream has been read from or cancelled.
+v16.8.0
+Static toExperimental A utility method for creating a web ReadableStream from a Readable.
v17.0.0
+Optional _constructThe readable.read() method reads data out of the internal buffer and
+returns it. If no data is available to be read, null is returned. By default,
+the data is returned as a Buffer object unless an encoding has been
+specified using the readable.setEncoding() method or the stream is operating
+in object mode.
The optional size argument specifies a specific number of bytes to read. Ifsize bytes are not available to be read, null will be returned _unless_the stream has ended, in which
+case all of the data remaining in the internal
+buffer will be returned.
If the size argument is not specified, all of the data contained in the
+internal buffer will be returned.
The size argument must be less than or equal to 1 GiB.
The readable.read() method should only be called on Readable streams
+operating in paused mode. In flowing mode, readable.read() is called
+automatically until the internal buffer is fully drained.
const readable = getReadableStreamSomehow();
// 'readable' may be triggered multiple times as data is buffered in
readable.on('readable', () => {
let chunk;
console.log('Stream is readable (new data received in buffer)');
// Use a loop to make sure we read all currently available data
while (null !== (chunk = readable.read())) {
console.log(`Read ${chunk.length} bytes of data...`);
}
});
// 'end' will be triggered once when there is no more data available
readable.on('end', () => {
console.log('Reached end of stream.');
});
+
+Each call to readable.read() returns a chunk of data, or null. The chunks
+are not concatenated. A while loop is necessary to consume all data
+currently in the buffer. When reading a large file .read() may return null,
+having consumed all buffered content so far, but there is still more data to
+come not yet buffered. In this case a new 'readable' event will be emitted
+when there is more data in the buffer. Finally the 'end' event will be
+emitted when there is no more data to come.
Therefore to read a file's whole contents from a readable, it is necessary
+to collect chunks across multiple 'readable' events:
const chunks = [];
readable.on('readable', () => {
let chunk;
while (null !== (chunk = readable.read())) {
chunks.push(chunk);
}
});
readable.on('end', () => {
const content = chunks.join('');
});
+
+A Readable stream in object mode will always return a single item from
+a call to readable.read(size), regardless of the value of thesize argument.
If the readable.read() method returns a chunk of data, a 'data' event will
+also be emitted.
Calling read after the 'end' event has
+been emitted will return null. No runtime error will be raised.
Optional size: numberOptional argument to specify how much data to read.
+v0.9.4
+The readable.setEncoding() method sets the character encoding for
+data read from the Readable stream.
By default, no encoding is assigned and stream data will be returned asBuffer objects. Setting an encoding causes the stream data
+to be returned as strings of the specified encoding rather than as Bufferobjects. For instance, calling readable.setEncoding('utf8') will cause the
+output data to be interpreted as UTF-8 data, and passed as strings. Callingreadable.setEncoding('hex') will cause the data to be encoded in hexadecimal
+string format.
The Readable stream will properly handle multi-byte characters delivered
+through the stream that would otherwise become improperly decoded if simply
+pulled from the stream as Buffer objects.
const readable = getReadableStreamSomehow();
readable.setEncoding('utf8');
readable.on('data', (chunk) => {
assert.equal(typeof chunk, 'string');
console.log('Got %d characters of string data:', chunk.length);
});
+
+The encoding to use.
+v0.9.4
+The readable.pause() method will cause a stream in flowing mode to stop
+emitting 'data' events, switching out of flowing mode. Any data that
+becomes available will remain in the internal buffer.
const readable = getReadableStreamSomehow();
readable.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
readable.pause();
console.log('There will be no additional data for 1 second.');
setTimeout(() => {
console.log('Now data will start flowing again.');
readable.resume();
}, 1000);
});
+
+The readable.pause() method has no effect if there is a 'readable'event listener.
v0.9.4
+The readable.resume() method causes an explicitly paused Readable stream to
+resume emitting 'data' events, switching the stream into flowing mode.
The readable.resume() method can be used to fully consume the data from a
+stream without actually processing any of that data:
getReadableStreamSomehow()
.resume()
.on('end', () => {
console.log('Reached the end, but did not read anything.');
});
+
+The readable.resume() method has no effect if there is a 'readable'event listener.
v0.9.4
+The readable.isPaused() method returns the current operating state of theReadable. This is used primarily by the mechanism that underlies thereadable.pipe() method. In most
+typical cases, there will be no reason to
+use this method directly.
const readable = new stream.Readable();
readable.isPaused(); // === false
readable.pause();
readable.isPaused(); // === true
readable.resume();
readable.isPaused(); // === false
+
+v0.11.14
+The readable.unpipe() method detaches a Writable stream previously attached
+using the pipe method.
If the destination is not specified, then all pipes are detached.
If the destination is specified, but no pipe is set up for it, then
+the method does nothing.
const fs = require('fs');
const readable = getReadableStreamSomehow();
const writable = fs.createWriteStream('file.txt');
// All the data from readable goes into 'file.txt',
// but only for the first second.
readable.pipe(writable);
setTimeout(() => {
console.log('Stop writing to file.txt.');
readable.unpipe(writable);
console.log('Manually close the file stream.');
writable.end();
}, 1000);
+
+Optional destination: WritableStreamOptional specific stream to unpipe
+v0.9.4
+Passing chunk as null signals the end of the stream (EOF) and behaves the
+same as readable.push(null), after which no more data can be written. The EOF
+signal is put at the end of the buffer and any buffered data will still be
+flushed.
The readable.unshift() method pushes a chunk of data back into the internal
+buffer. This is useful in certain situations where a stream is being consumed by
+code that needs to "un-consume" some amount of data that it has optimistically
+pulled out of the source, so that the data can be passed on to some other party.
The stream.unshift(chunk) method cannot be called after the 'end' event
+has been emitted or a runtime error will be thrown.
Developers using stream.unshift() often should consider switching to
+use of a Transform stream instead. See the API for stream implementers section for more information.
// Pull off a header delimited by \n\n.
// Use unshift() if we get too much.
// Call the callback with (error, header, stream).
const { StringDecoder } = require('string_decoder');
function parseHeader(stream, callback) {
stream.on('error', callback);
stream.on('readable', onReadable);
const decoder = new StringDecoder('utf8');
let header = '';
function onReadable() {
let chunk;
while (null !== (chunk = stream.read())) {
const str = decoder.write(chunk);
if (str.includes('\n\n')) {
// Found the header boundary.
const split = str.split(/\n\n/);
header += split.shift();
const remaining = split.join('\n\n');
const buf = Buffer.from(remaining, 'utf8');
stream.removeListener('error', callback);
// Remove the 'readable' listener before unshifting.
stream.removeListener('readable', onReadable);
if (buf.length)
stream.unshift(buf);
// Now the body of the message can be read from the stream.
callback(null, header, stream);
return;
}
// Still reading the header.
header += str;
}
}
}
+
+Unlike push, stream.unshift(chunk) will not
+end the reading process by resetting the internal reading state of the stream.
+This can cause unexpected results if readable.unshift() is called during a
+read (i.e. from within a _read implementation on a
+custom stream). Following the call to readable.unshift() with an immediate push will reset the reading state appropriately,
+however it is best to simply avoid calling readable.unshift() while in the
+process of performing a read.
Chunk of data to unshift onto the read queue. For streams not operating in object mode, chunk must be a string, Buffer, Uint8Array or null. For object mode
+streams, chunk may be any JavaScript value.
Optional encoding: BufferEncodingEncoding of string chunks. Must be a valid Buffer encoding, such as 'utf8' or 'ascii'.
v0.9.11
+Prior to Node.js 0.10, streams did not implement the entire stream module API
+as it is currently defined. (See Compatibility for more information.)
When using an older Node.js library that emits 'data' events and has a pause method that is advisory only, thereadable.wrap() method can be used to create a Readable
+stream that uses
+the old stream as its data source.
It will rarely be necessary to use readable.wrap() but the method has been
+provided as a convenience for interacting with older Node.js applications and
+libraries.
const { OldReader } = require('./old-api-module.js');
const { Readable } = require('stream');
const oreader = new OldReader();
const myReader = new Readable().wrap(oreader);
myReader.on('readable', () => {
myReader.read(); // etc.
});
+
+An "old style" readable stream
+v0.9.4
+Optional encoding: BufferEncodingThe iterator created by this method gives users the option to cancel the destruction
+of the stream if the for await...of loop is exited by return, break, or throw,
+or if the iterator should destroy the stream if the stream emitted an error during iteration.
Optional options: { Optional destroyWhen set to false, calling return on the async iterator,
+or exiting a for await...of iteration using a break, return, or throw will not destroy the stream.
+Default: true.
v16.3.0
+This method allows mapping over the stream. The fn function will be called for every chunk in the stream.
+If the fn function returns a promise - that promise will be awaited before being passed to the result stream.
a function to map over every chunk in the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa stream mapped with the function fn.
+v17.4.0, v16.14.0
+This method allows filtering the stream. For each chunk in the stream the fn function will be called
+and if it returns a truthy value, the chunk will be passed to the result stream.
+If the fn function returns a promise - that promise will be awaited.
a function to filter chunks from the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa stream filtered with the predicate fn.
+v17.4.0, v16.14.0
+This method allows iterating a stream. For each chunk in the stream the fn function will be called.
+If the fn function returns a promise - that promise will be awaited.
This method is different from for await...of loops in that it can optionally process chunks concurrently.
+In addition, a forEach iteration can only be stopped by having passed a signal option
+and aborting the related AbortController while for await...of can be stopped with break or return.
+In either case the stream will be destroyed.
This method is different from listening to the 'data' event in that it uses the readable event
+in the underlying machinary and can limit the number of concurrent fn calls.
a function to call on each chunk of the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa promise for when the stream has finished.
+v17.5.0
+This method allows easily obtaining the contents of a stream.
+As this method reads the entire stream into memory, it negates the benefits of streams. It's intended +for interoperability and convenience, not as the primary way to consume streams.
+Optional options: Pick<ArrayOptions, "signal">a promise containing an array with the contents of the stream.
+v17.5.0
+This method is similar to Array.prototype.some and calls fn on each chunk in the stream
+until the awaited return value is true (or any truthy value). Once an fn call on a chunk
+awaited return value is truthy, the stream is destroyed and the promise is fulfilled with true.
+If none of the fn calls on the chunks return a truthy value, the promise is fulfilled with false.
a function to call on each chunk of the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa promise evaluating to true if fn returned a truthy value for at least one of the chunks.
v17.5.0
+This method is similar to Array.prototype.find and calls fn on each chunk in the stream
+to find a chunk with a truthy value for fn. Once an fn call's awaited return value is truthy,
+the stream is destroyed and the promise is fulfilled with value for which fn returned a truthy value.
+If all of the fn calls on the chunks return a falsy value, the promise is fulfilled with undefined.
a function to call on each chunk of the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa promise evaluating to the first chunk for which fn evaluated with a truthy value,
+or undefined if no element was found.
v17.5.0
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsThis method is similar to Array.prototype.every and calls fn on each chunk in the stream
+to check if all awaited return values are truthy value for fn. Once an fn call on a chunk
+awaited return value is falsy, the stream is destroyed and the promise is fulfilled with false.
+If all of the fn calls on the chunks return a truthy value, the promise is fulfilled with true.
a function to call on each chunk of the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa promise evaluating to true if fn returned a truthy value for every one of the chunks.
v17.5.0
+This method returns a new stream by applying the given callback to each chunk of the stream +and then flattening the result.
+It is possible to return a stream or another iterable or async iterable from fn and the result streams +will be merged (flattened) into the returned stream.
+a function to map over every chunk in the stream. May be async. May be a stream or generator.
+Optional options: Pick<ArrayOptions, "signal">Optional options: ArrayOptionsa stream flat-mapped with the function fn.
+v17.5.0
+This method returns a new stream with the first limit chunks dropped from the start.
+the number of chunks to drop from the readable.
+Optional options: Pick<ArrayOptions, "signal">a stream with limit chunks dropped from the start.
+v17.5.0
+This method returns a new stream with the first limit chunks.
+the number of chunks to take from the readable.
+Optional options: Pick<ArrayOptions, "signal">a stream with limit chunks taken.
+v17.5.0
+This method returns a new stream with chunks of the underlying stream paired with a counter
+in the form [index, chunk]. The first index value is 0 and it increases by 1 for each chunk produced.
Optional options: Pick<ArrayOptions, "signal">a stream of indexed pairs.
+v17.5.0
+This method calls fn on each chunk of the stream in order, passing it the result from the calculation +on the previous element. It returns a promise for the final value of the reduction.
+If no initial value is supplied the first chunk of the stream is used as the initial value.
+If the stream is empty, the promise is rejected with a TypeError with the ERR_INVALID_ARGS code property.
The reducer function iterates the stream element-by-element which means that there is no concurrency parameter
+or parallelism. To perform a reduce concurrently, you can extract the async function to readable.map method.
a reducer function to call over every chunk in the stream. Async or not.
+Optional options: Pick<ArrayOptions, "signal">Optional initial: undefinedthe initial value to use in the reduction.
+Optional options: Pick<ArrayOptions, "signal">a promise for the final value of the reduction.
+v17.5.0
+Optional options: Pick<ArrayOptions, "signal">Optional options: Pick<ArrayOptions, "signal">Destroy the stream. Optionally emit an 'error' event, and emit a 'close'event (unless emitClose is set to false). After this call, the readable
+stream will release any internal resources and subsequent calls to push()will be ignored.
Once destroy() has been called any further calls will be a no-op and no
+further errors except from _destroy() may be emitted as 'error'.
Implementors should not override this method, but instead implement readable._destroy().
Optional error: ErrorError which will be passed as payload in 'error' event
v8.0.0
+Static fromA utility method for creating duplex streams.
+Stream converts writable stream into writable Duplex and readable stream
+to Duplex.Blob converts into readable Duplex.string converts into readable Duplex.ArrayBuffer converts into readable Duplex.AsyncIterable converts into a readable Duplex. Cannot yield null.AsyncGeneratorFunction converts into a readable/writable transform
+Duplex. Must take a source AsyncIterable as first parameter. Cannot yield
+null.AsyncFunction converts into a writable Duplex. Must return
+either null or undefinedObject ({ writable, readable }) converts readable and
+writable into Stream and then combines them into Duplex where the
+Duplex will write to the writable and read from the readable.Promise converts into readable Duplex. Value null is ignored.v16.8.0
+Optional error: ErrorOptional _writevOptional error: ErrorThe writable.write() method writes some data to the stream, and calls the
+supplied callback once the data has been fully handled. If an error
+occurs, the callback will be called with the error as its
+first argument. The callback is called asynchronously and before 'error' is
+emitted.
The return value is true if the internal buffer is less than thehighWaterMark configured when the stream was created after admitting chunk.
+If false is returned, further attempts to write data to the stream should
+stop until the 'drain' event is emitted.
While a stream is not draining, calls to write() will buffer chunk, and
+return false. Once all currently buffered chunks are drained (accepted for
+delivery by the operating system), the 'drain' event will be emitted.
+Once write() returns false, do not write more chunks
+until the 'drain' event is emitted. While calling write() on a stream that
+is not draining is allowed, Node.js will buffer all written chunks until
+maximum memory usage occurs, at which point it will abort unconditionally.
+Even before it aborts, high memory usage will cause poor garbage collector
+performance and high RSS (which is not typically released back to the system,
+even after the memory is no longer required). Since TCP sockets may never
+drain if the remote peer does not read the data, writing a socket that is
+not draining may lead to a remotely exploitable vulnerability.
Writing data while the stream is not draining is particularly
+problematic for a Transform, because the Transform streams are paused
+by default until they are piped or a 'data' or 'readable' event handler
+is added.
If the data to be written can be generated or fetched on demand, it is
+recommended to encapsulate the logic into a Readable and use pipe. However, if calling write() is preferred, it is
+possible to respect backpressure and avoid memory issues using the 'drain' event:
function write(data, cb) {
if (!stream.write(data)) {
stream.once('drain', cb);
} else {
process.nextTick(cb);
}
}
// Wait for cb to be called before doing any other write.
write('hello', () => {
console.log('Write completed, do more writes now.');
});
+
+A Writable stream in object mode will always ignore the encoding argument.
Optional data to write. For streams not operating in object mode, chunk must be a string, Buffer or Uint8Array. For object mode streams, chunk may be any
+JavaScript value other than null.
Optional encoding: BufferEncodingCallback for when this chunk of data is flushed.
+Optional cb: ((error) => void)false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.
v0.9.4
+Optional cb: ((error) => void)The writable.setDefaultEncoding() method sets the default encoding for a Writable stream.
The new default encoding
+v0.11.15
+Calling the writable.end() method signals that no more data will be written
+to the Writable. The optional chunk and encoding arguments allow one
+final additional chunk of data to be written immediately before closing the
+stream.
Calling the write method after calling end will raise an error.
+// Write 'hello, ' and then end with 'world!'.
const fs = require('fs');
const file = fs.createWriteStream('example.txt');
file.write('hello, ');
file.end('world!');
// Writing more now is not allowed!
+
+Optional cb: (() => void)v0.9.4
+Optional cb: (() => void)Optional encoding: BufferEncodingOptional cb: (() => void)The writable.cork() method forces all written data to be buffered in memory.
+The buffered data will be flushed when either the uncork or end methods are called.
The primary intent of writable.cork() is to accommodate a situation in which
+several small chunks are written to the stream in rapid succession. Instead of
+immediately forwarding them to the underlying destination, writable.cork()buffers all the chunks until writable.uncork() is called, which will pass them
+all to writable._writev(), if present. This prevents a head-of-line blocking
+situation where data is being buffered while waiting for the first small chunk
+to be processed. However, use of writable.cork() without implementingwritable._writev() may have an adverse effect on throughput.
See also: writable.uncork(), writable._writev().
v0.11.2
+The writable.uncork() method flushes all data buffered since cork was called.
When using writable.cork() and writable.uncork() to manage the buffering
+of writes to a stream, defer calls to writable.uncork() usingprocess.nextTick(). Doing so allows batching of allwritable.write() calls that occur within a given Node.js event
+loop phase.
stream.cork();
stream.write('some ');
stream.write('data ');
process.nextTick(() => stream.uncork());
+
+If the writable.cork() method is called multiple times on a stream, the
+same number of calls to writable.uncork() must be called to flush the buffered
+data.
stream.cork();
stream.write('some ');
stream.cork();
stream.write('data ');
process.nextTick(() => {
stream.uncork();
// The data will not be flushed until uncork() is called a second time.
stream.uncork();
});
+
+See also: writable.cork().
v0.11.2
+Event emitter +The defined events on documents including:
+Rest ...args: any[]Synchronously calls each of the listeners registered for the event namedeventName, in the order they were registered, passing the supplied arguments
+to each.
Returns true if the event had listeners, false otherwise.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
+
+v0.1.26
+Rest ...args: any[]Adds the listener function to the end of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple
+times.
server.on('connection', (stream) => {
console.log('someone connected!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. Theemitter.prependListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+The name of the event.
+The callback function
+v0.1.101
+Rest ...args: any[]Adds a one-timelistener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. Theemitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+The name of the event.
+The callback function
+v0.3.0
+Rest ...args: any[]Adds the listener function to the beginning of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple
+times.
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+v6.0.0
+Rest ...args: any[]Adds a one-timelistener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+v6.0.0
+Rest ...args: any[]Removes the specified listener from the listener array for the event namedeventName.
const callback = (stream) => {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
+
+removeListener() will remove, at most, one instance of a listener from the
+listener array. If any single listener has been added multiple times to the
+listener array for the specified eventName, then removeListener() must be
+called multiple times to remove each instance.
Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that anyremoveListener() or removeAllListeners() calls after emitting and before the last listener finishes execution
+will not remove them fromemit() in progress. Subsequent events behave as expected.
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners() method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener() will remove the most
+recently added instance. In the example the once('ping')listener is removed:
const ee = new EventEmitter();
function pong() {
console.log('pong');
}
ee.on('ping', pong);
ee.once('ping', pong);
ee.removeListener('ping', pong);
ee.emit('ping');
ee.emit('ping');
+
+Returns a reference to the EventEmitter, so that calls can be chained.
v0.1.26
+Rest ...args: any[]Generated using TypeDoc
The EventEmitter class is defined and exposed by the events module:
const EventEmitter = require('events');
+
+All EventEmitters emit the event 'newListener' when new listeners are
+added and 'removeListener' when existing listeners are removed.
It supports the following option:
+v0.1.26
+Optional options: EventEmitterOptionsStatic Readonly errorThis symbol shall be used to install a listener for only monitoring 'error'
+events. Listeners installed using this symbol are called before the regular
+'error' listeners are called.
Installing a listener using this symbol does not change the behavior once an
+'error' event is emitted, therefore the process will still crash if no
+regular 'error' listener is installed.
Static Readonly captureStatic captureSets or gets the default captureRejection value for all emitters.
+Static defaultOptional [captureStatic onceCreates a Promise that is fulfilled when the EventEmitter emits the given
+event or that is rejected if the EventEmitter emits 'error' while waiting.
+The Promise will resolve with an array of all the arguments emitted to the
+given event.
This method is intentionally generic and works with the web platform EventTarget interface, which has no special'error' event
+semantics and does not listen to the 'error' event.
const { once, EventEmitter } = require('events');
async function run() {
const ee = new EventEmitter();
process.nextTick(() => {
ee.emit('myevent', 42);
});
const [value] = await once(ee, 'myevent');
console.log(value);
const err = new Error('kaboom');
process.nextTick(() => {
ee.emit('error', err);
});
try {
await once(ee, 'myevent');
} catch (err) {
console.log('error happened', err);
}
}
run();
+
+The special handling of the 'error' event is only used when events.once()is used to wait for another event. If events.once() is used to wait for the
+'error' event itself, then it is treated as any other kind of event without
+special handling:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
once(ee, 'error')
.then(([err]) => console.log('ok', err.message))
.catch((err) => console.log('error', err.message));
ee.emit('error', new Error('boom'));
// Prints: ok boom
+
+An AbortSignal can be used to cancel waiting for the event:
const { EventEmitter, once } = require('events');
const ee = new EventEmitter();
const ac = new AbortController();
async function foo(emitter, event, signal) {
try {
await once(emitter, event, { signal });
console.log('event emitted!');
} catch (error) {
if (error.name === 'AbortError') {
console.error('Waiting for the event was canceled!');
} else {
console.error('There was an error', error.message);
}
}
}
foo(ee, 'foo', ac.signal);
ac.abort(); // Abort waiting for the event
ee.emit('foo'); // Prints: Waiting for the event was canceled!
+
+Optional options: StaticEventEmitterOptionsv11.13.0, v10.16.0
+Optional options: StaticEventEmitterOptionsStatic onconst { on, EventEmitter } = require('events');
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo')) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
+
+Returns an AsyncIterator that iterates eventName events. It will throw
+if the EventEmitter emits 'error'. It removes all listeners when
+exiting the loop. The value returned by each iteration is an array
+composed of the emitted event arguments.
An AbortSignal can be used to cancel waiting on events:
const { on, EventEmitter } = require('events');
const ac = new AbortController();
(async () => {
const ee = new EventEmitter();
// Emit later on
process.nextTick(() => {
ee.emit('foo', 'bar');
ee.emit('foo', 42);
});
for await (const event of on(ee, 'foo', { signal: ac.signal })) {
// The execution of this inner block is synchronous and it
// processes one event at a time (even with await). Do not use
// if concurrent execution is required.
console.log(event); // prints ['bar'] [42]
}
// Unreachable here
})();
process.nextTick(() => ac.abort());
+
+The name of the event being listened for
+Optional options: StaticEventEmitterOptionsthat iterates eventName events emitted by the emitter
v13.6.0, v12.16.0
+Static listenerA class method that returns the number of listeners for the given eventNameregistered on the given emitter.
const { EventEmitter, listenerCount } = require('events');
const myEmitter = new EventEmitter();
myEmitter.on('event', () => {});
myEmitter.on('event', () => {});
console.log(listenerCount(myEmitter, 'event'));
// Prints: 2
+
+The emitter to query
+The event name
+v0.9.12
+Since v3.2.0 - Use listenerCount instead.
Static getReturns a copy of the array of listeners for the event named eventName.
For EventEmitters this behaves exactly the same as calling .listeners on
+the emitter.
For EventTargets this is the only way to get the event listeners for the
+event target. This is useful for debugging and diagnostic purposes.
const { getEventListeners, EventEmitter } = require('events');
{
const ee = new EventEmitter();
const listener = () => console.log('Events are fun');
ee.on('foo', listener);
getEventListeners(ee, 'foo'); // [listener]
}
{
const et = new EventTarget();
const listener = () => console.log('Events are fun');
et.addEventListener('foo', listener);
getEventListeners(et, 'foo'); // [listener]
}
+
+v15.2.0, v14.17.0
+Static getReturns the currently set max amount of listeners.
+For EventEmitters this behaves exactly the same as calling .getMaxListeners on
+the emitter.
For EventTargets this is the only way to get the max event listeners for the
+event target. If the number of event handlers on a single EventTarget exceeds
+the max set, the EventTarget will print a warning.
import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events';
{
const ee = new EventEmitter();
console.log(getMaxListeners(ee)); // 10
setMaxListeners(11, ee);
console.log(getMaxListeners(ee)); // 11
}
{
const et = new EventTarget();
console.log(getMaxListeners(et)); // 10
setMaxListeners(11, et);
console.log(getMaxListeners(et)); // 11
}
+
+v18.17.0
+Static setconst {
setMaxListeners,
EventEmitter
} = require('events');
const target = new EventTarget();
const emitter = new EventEmitter();
setMaxListeners(5, target, emitter);
+
+Optional n: numberA non-negative number. The maximum number of listeners per EventTarget event.
Rest ...eventTargets: (EventEmitter<DefaultEventMap> | _DOMEventTarget)[]v15.4.0
+Static addExperimental Listens once to the abort event on the provided signal.
Listening to the abort event on abort signals is unsafe and may
+lead to resource leaks since another third party with the signal can
+call e.stopImmediatePropagation(). Unfortunately Node.js cannot change
+this since it would violate the web standard. Additionally, the original
+API makes it easy to forget to remove listeners.
This API allows safely using AbortSignals in Node.js APIs by solving these
+two issues by listening to the event such that stopImmediatePropagation does
+not prevent the listener from running.
Returns a disposable so that it may be unsubscribed from more easily.
+import { addAbortListener } from 'node:events';
function example(signal) {
let disposable;
try {
signal.addEventListener('abort', (e) => e.stopImmediatePropagation());
disposable = addAbortListener(signal, (e) => {
// Do something when signal is aborted.
});
} finally {
disposable?.[Symbol.dispose]();
}
}
+
+Disposable that removes the abort listener.
v18.18.0
+Alias for emitter.on(eventName, listener).
Rest ...args: any[]v0.1.26
+Adds the listener function to the end of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple
+times.
server.on('connection', (stream) => {
console.log('someone connected!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. Theemitter.prependListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.on('foo', () => console.log('a'));
myEE.prependListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+The name of the event.
+The callback function
+Rest ...args: any[]v0.1.101
+Adds a one-timelistener function for the event named eventName. The
+next time eventName is triggered, this listener is removed and then invoked.
server.once('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
By default, event listeners are invoked in the order they are added. Theemitter.prependOnceListener() method can be used as an alternative to add the
+event listener to the beginning of the listeners array.
const myEE = new EventEmitter();
myEE.once('foo', () => console.log('a'));
myEE.prependOnceListener('foo', () => console.log('b'));
myEE.emit('foo');
// Prints:
// b
// a
+
+The name of the event.
+The callback function
+Rest ...args: any[]v0.3.0
+Removes the specified listener from the listener array for the event namedeventName.
const callback = (stream) => {
console.log('someone connected!');
};
server.on('connection', callback);
// ...
server.removeListener('connection', callback);
+
+removeListener() will remove, at most, one instance of a listener from the
+listener array. If any single listener has been added multiple times to the
+listener array for the specified eventName, then removeListener() must be
+called multiple times to remove each instance.
Once an event is emitted, all listeners attached to it at the
+time of emitting are called in order. This implies that anyremoveListener() or removeAllListeners() calls after emitting and before the last listener finishes execution
+will not remove them fromemit() in progress. Subsequent events behave as expected.
const myEmitter = new MyEmitter();
const callbackA = () => {
console.log('A');
myEmitter.removeListener('event', callbackB);
};
const callbackB = () => {
console.log('B');
};
myEmitter.on('event', callbackA);
myEmitter.on('event', callbackB);
// callbackA removes listener callbackB but it will still be called.
// Internal listener array at time of emit [callbackA, callbackB]
myEmitter.emit('event');
// Prints:
// A
// B
// callbackB is now removed.
// Internal listener array [callbackA]
myEmitter.emit('event');
// Prints:
// A
+
+Because listeners are managed using an internal array, calling this will
+change the position indices of any listener registered after the listener
+being removed. This will not impact the order in which listeners are called,
+but it means that any copies of the listener array as returned by
+the emitter.listeners() method will need to be recreated.
When a single function has been added as a handler multiple times for a single
+event (as in the example below), removeListener() will remove the most
+recently added instance. In the example the once('ping')listener is removed:
const ee = new EventEmitter();
function pong() {
console.log('pong');
}
ee.on('ping', pong);
ee.once('ping', pong);
ee.removeListener('ping', pong);
ee.emit('ping');
ee.emit('ping');
+
+Returns a reference to the EventEmitter, so that calls can be chained.
Rest ...args: any[]v0.1.26
+Alias for emitter.removeListener().
Rest ...args: any[]v10.0.0
+Removes all listeners, or those of the specified eventName.
It is bad practice to remove listeners added elsewhere in the code,
+particularly when the EventEmitter instance was created by some other
+component or module (e.g. sockets or file streams).
Returns a reference to the EventEmitter, so that calls can be chained.
Optional event: string | symbolv0.1.26
+By default EventEmitters will print a warning if more than 10 listeners are
+added for a particular event. This is a useful default that helps finding
+memory leaks. The emitter.setMaxListeners() method allows the limit to be
+modified for this specific EventEmitter instance. The value can be set toInfinity (or 0) to indicate an unlimited number of listeners.
Returns a reference to the EventEmitter, so that calls can be chained.
v0.3.5
+Returns the current max listener value for the EventEmitter which is either
+set by emitter.setMaxListeners(n) or defaults to defaultMaxListeners.
v1.0.0
+Returns a copy of the array of listeners for the event named eventName.
server.on('connection', (stream) => {
console.log('someone connected!');
});
console.log(util.inspect(server.listeners('connection')));
// Prints: [ [Function] ]
+
+v0.1.26
+Returns a copy of the array of listeners for the event named eventName,
+including any wrappers (such as those created by .once()).
const emitter = new EventEmitter();
emitter.once('log', () => console.log('log once'));
// Returns a new Array with a function `onceWrapper` which has a property
// `listener` which contains the original listener bound above
const listeners = emitter.rawListeners('log');
const logFnWrapper = listeners[0];
// Logs "log once" to the console and does not unbind the `once` event
logFnWrapper.listener();
// Logs "log once" to the console and removes the listener
logFnWrapper();
emitter.on('log', () => console.log('log persistently'));
// Will return a new Array with a single function bound by `.on()` above
const newListeners = emitter.rawListeners('log');
// Logs "log persistently" twice
newListeners[0]();
emitter.emit('log');
+
+v9.4.0
+Synchronously calls each of the listeners registered for the event namedeventName, in the order they were registered, passing the supplied arguments
+to each.
Returns true if the event had listeners, false otherwise.
const EventEmitter = require('events');
const myEmitter = new EventEmitter();
// First listener
myEmitter.on('event', function firstListener() {
console.log('Helloooo! first listener');
});
// Second listener
myEmitter.on('event', function secondListener(arg1, arg2) {
console.log(`event with parameters ${arg1}, ${arg2} in second listener`);
});
// Third listener
myEmitter.on('event', function thirdListener(...args) {
const parameters = args.join(', ');
console.log(`event with parameters ${parameters} in third listener`);
});
console.log(myEmitter.listeners('event'));
myEmitter.emit('event', 1, 2, 3, 4, 5);
// Prints:
// [
// [Function: firstListener],
// [Function: secondListener],
// [Function: thirdListener]
// ]
// Helloooo! first listener
// event with parameters 1, 2 in second listener
// event with parameters 1, 2, 3, 4, 5 in third listener
+
+Rest ...args: AnyRestv0.1.26
+Returns the number of listeners listening to the event named eventName.
If listener is provided, it will return how many times the listener
+is found in the list of the listeners of the event.
The name of the event being listened for
+Optional listener: FunctionThe event handler function
+v3.2.0
+Adds the listener function to the beginning of the listeners array for the
+event named eventName. No checks are made to see if the listener has
+already been added. Multiple calls passing the same combination of eventNameand listener will result in the listener being added, and called, multiple
+times.
server.prependListener('connection', (stream) => {
console.log('someone connected!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+Rest ...args: any[]v6.0.0
+Adds a one-timelistener function for the event named eventName to the beginning of the listeners array. The next time eventName is triggered, this
+listener is removed, and then invoked.
server.prependOnceListener('connection', (stream) => {
console.log('Ah, we have our first user!');
});
+
+Returns a reference to the EventEmitter, so that calls can be chained.
The name of the event.
+The callback function
+Rest ...args: any[]v6.0.0
+Returns an array listing the events for which the emitter has registered
+listeners. The values in the array are strings or Symbols.
const EventEmitter = require('events');
const myEE = new EventEmitter();
myEE.on('foo', () => {});
myEE.on('bar', () => {});
const sym = Symbol('symbol');
myEE.on(sym, () => {});
console.log(myEE.eventNames());
// Prints: [ 'foo', 'bar', Symbol(symbol) ]
+
+v6.0.0
+Optional options: { Optional end?: booleanOptional options: { Generated using TypeDoc
'removeListener' when existing listeners are removed.
It supports the following option:
v0.1.26
-Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Generated using TypeDoc
Optional options: FinishedOptionsGenerated using TypeDoc
Optional options: PipelineOptionsOptional options: PipelineOptionsOptional options: PipelineOptionsOptional options: PipelineOptionsRest ...streams: (WritableStream | ReadWriteStream | PipelineOptions)[]Generated using TypeDoc
Attaches an AbortSignal to a readable or writeable stream. This lets code
+control stream destruction using an AbortController.
Calling abort on the AbortController corresponding to the passedAbortSignal will behave the same way as calling .destroy(new AbortError())on the stream.
const fs = require('fs');
const controller = new AbortController();
const read = addAbortSignal(
controller.signal,
fs.createReadStream(('object.json'))
);
// Later, abort the operation closing the stream
controller.abort();
+
+Or using an AbortSignal with a readable stream as an async iterable:
const controller = new AbortController();
setTimeout(() => controller.abort(), 10_000); // set a timeout
const stream = addAbortSignal(
controller.signal,
fs.createReadStream(('object.json'))
);
(async () => {
try {
for await (const chunk of stream) {
await process(chunk);
}
} catch (e) {
if (e.name === 'AbortError') {
// The operation was cancelled
} else {
throw e;
}
}
})();
+
+A signal representing possible cancellation
+a stream to attach a signal to
+v15.4.0
+Generated using TypeDoc
Optional options: FinishedOptionsGenerated using TypeDoc
A function to get notified when a stream is no longer readable, writable +or has experienced an error or a premature close event.
+const { finished } = require('stream');
const rs = fs.createReadStream('archive.tar');
finished(rs, (err) => {
if (err) {
console.error('Stream failed.', err);
} else {
console.log('Stream is done reading.');
}
});
rs.resume(); // Drain the stream.
+
+Especially useful in error handling scenarios where a stream is destroyed
+prematurely (like an aborted HTTP request), and will not emit 'end'or 'finish'.
The finished API provides promise version:
const { finished } = require('stream/promises');
const rs = fs.createReadStream('archive.tar');
async function run() {
await finished(rs);
console.log('Stream is done reading.');
}
run().catch(console.error);
rs.resume(); // Drain the stream.
+
+stream.finished() leaves dangling event listeners (in particular'error', 'end', 'finish' and 'close') after callback has been
+invoked. The reason for this is so that unexpected 'error' events (due to
+incorrect stream implementations) do not cause unexpected crashes.
+If this is unwanted behavior then the returned cleanup function needs to be
+invoked in the callback:
const cleanup = finished(rs, (err) => {
cleanup();
// ...
});
+
+A readable and/or writable stream.
+A callback function that takes an optional error argument.
+Optional err: ErrnoExceptionA cleanup function which removes all registered listeners.
+v10.0.0
+Optional err: ErrnoExceptionGenerated using TypeDoc
Generated using TypeDoc
Returns whether the stream has encountered an error.
+v17.3.0
+Generated using TypeDoc
Returns whether the stream is readable.
+v17.4.0
+Generated using TypeDoc
Optional options: PipelineOptionsOptional options: PipelineOptionsOptional options: PipelineOptionsOptional options: PipelineOptionsRest ...streams: (WritableStream | ReadWriteStream | PipelineOptions)[]Generated using TypeDoc
A module method to pipe between streams and generators forwarding errors and +properly cleaning up and provide a callback when the pipeline is complete.
+const { pipeline } = require('stream');
const fs = require('fs');
const zlib = require('zlib');
// Use the pipeline API to easily pipe a series of streams
// together and get notified when the pipeline is fully done.
// A pipeline to gzip a potentially huge tar file efficiently:
pipeline(
fs.createReadStream('archive.tar'),
zlib.createGzip(),
fs.createWriteStream('archive.tar.gz'),
(err) => {
if (err) {
console.error('Pipeline failed.', err);
} else {
console.log('Pipeline succeeded.');
}
}
);
+
+The pipeline API provides a promise version, which can also
+receive an options argument as the last parameter with asignal AbortSignal property. When the signal is aborted,destroy will be called on the underlying pipeline, with
+anAbortError.
const { pipeline } = require('stream/promises');
async function run() {
await pipeline(
fs.createReadStream('archive.tar'),
zlib.createGzip(),
fs.createWriteStream('archive.tar.gz')
);
console.log('Pipeline succeeded.');
}
run().catch(console.error);
+
+To use an AbortSignal, pass it inside an options object,
+as the last argument:
const { pipeline } = require('stream/promises');
async function run() {
const ac = new AbortController();
const signal = ac.signal;
setTimeout(() => ac.abort(), 1);
await pipeline(
fs.createReadStream('archive.tar'),
zlib.createGzip(),
fs.createWriteStream('archive.tar.gz'),
{ signal },
);
}
run().catch(console.error); // AbortError
+
+The pipeline API also supports async generators:
const { pipeline } = require('stream/promises');
const fs = require('fs');
async function run() {
await pipeline(
fs.createReadStream('lowercase.txt'),
async function* (source, { signal }) {
source.setEncoding('utf8'); // Work with strings rather than `Buffer`s.
for await (const chunk of source) {
yield await processChunk(chunk, { signal });
}
},
fs.createWriteStream('uppercase.txt')
);
console.log('Pipeline succeeded.');
}
run().catch(console.error);
+
+Remember to handle the signal argument passed into the async generator.
+Especially in the case where the async generator is the source for the
+pipeline (i.e. first argument) or the pipeline will never complete.
const { pipeline } = require('stream/promises');
const fs = require('fs');
async function run() {
await pipeline(
async function* ({ signal }) {
await someLongRunningfn({ signal });
yield 'asd';
},
fs.createWriteStream('uppercase.txt')
);
console.log('Pipeline succeeded.');
}
run().catch(console.error);
+
+stream.pipeline() will call stream.destroy(err) on all streams except:
Readable streams which have emitted 'end' or 'close'.Writable streams which have emitted 'finish' or 'close'.stream.pipeline() leaves dangling event listeners on the streams
+after the callback has been invoked. In the case of reuse of streams after
+failure, this can cause event listener leaks and swallowed errors. If the last
+stream is readable, dangling event listeners will be removed so that the last
+stream can be consumed later.
stream.pipeline() closes all the streams when an error is raised.
+The IncomingRequest usage with pipeline could lead to an unexpected behavior
+once it would destroy the socket without sending the expected response.
+See the example below:
const fs = require('fs');
const http = require('http');
const { pipeline } = require('stream');
const server = http.createServer((req, res) => {
const fileStream = fs.createReadStream('./fileNotExist.txt');
pipeline(fileStream, res, (err) => {
if (err) {
console.log(err); // No such file
// this message can't be sent once `pipeline` already destroyed the socket
return res.end('error!!!');
}
});
});
+
+Optional callback: PipelineCallback<B>Called when the pipeline is fully done.
+v10.0.0
+Optional callback: PipelineCallback<B>Optional callback: ((err) => void)Rest ...streams: (WritableStream | ReadWriteStream | ((err) => void))[]Generated using TypeDoc
Generated using TypeDoc
Creates a LogLevelStreamEntry stream that writes to a static file at or above the minimum level
Generated using TypeDoc
Generated using TypeDoc
A
+Blobencapsulates immutable, raw data that can be safely shared across +multiple worker threads.Since
v15.7.0, v14.18.0
+